我想读取一个文本文件test.txt
,其中txt的格式为
'Jon, Stacy, Simon, ..., Maverick'
我想将字符串作为保存到test2.txt
中
'Jon AS t1_Jon, Stacy AS t1_Stacy, Simon AS t1_Simon, ..., Maverick AS t1_Maverick'
可能偶尔会有断线,我想忽略这一点。我该如何以一种高效而简单的方式来做这件事?
附言:我想不出一个更合适的标题了,你怎么命名?
一个不错的方法是使用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
您可以试用
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