我想讀取test.txttxt 格式的文本檔案
'Jon, Stacy, Simon, ..., Maverick'
我想將字串保存test2.txt為
'Jon AS t1_Jon, Stacy AS t1_Stacy, Simon AS t1_Simon, ..., Maverick AS t1_Maverick'
可能時不時會有換行符,我想忽略它。我將如何以有效和簡單的方式做到這一點?
PS:我想不出一個更合適的標題,你會怎么命名?
uj5u.com熱心網友回復:
一種不錯的方法是使用 re 模塊。
import re
s_in = 'apple, banana, orange,\n mango, guava'
words = re.split(r'[,\n]\s*',s_in)
s_out = ', '.join([f'{word} AS t1_{word}' for word in words])
print(s_out)
結果:
apple AS t1_apple, banana AS t1_banana, orange AS t1_orange, mango AS t1_mango, guava AS t1_guava
uj5u.com熱心網友回復:
你可以試試這個
with open('test.txt') as f:
_lines = ''
for line in f.readlines():
words = line.split(',')
for word in words:
_word = f'{word} AS t1_{word}'
_lines =_word
_lines ='\n'
print(_lines)
結果
Jon AS t1_Jon Stacy AS t1_ Stacy Simon AS t1_ Simon ... AS t1_ ... Maverick
AS t1_ Maverick
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/426906.html
下一篇:用字典描述某個區域的檔案
