python 中逗号分隔字符串的文本操作
Text manipulation of a comma separated string in python
我想读取文本文件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'
可能偶尔会有一个换行符,我想忽略它。我将如何以高效简单的方式做到这一点?
PS: 想不出更合适的标题,你会怎么命名?
一个不错的方法是使用 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
我想读取文本文件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'
可能偶尔会有一个换行符,我想忽略它。我将如何以高效简单的方式做到这一点?
PS: 想不出更合适的标题,你会怎么命名?
一个不错的方法是使用 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