[英]How do I split delimited strings in a list when not all items are delimited in Python 3?
I have a column of strings in a text file w/oa header (test_in.txt): 我在带o头文件(test_in.txt)的文本文件中有一列字符串:
apple
orange
banana
grape;pear;plum
cherry
pineapple
That I would like to have read: 我想读:
apple
orange
banana
grape
pear
plum
cherry
pineapple
I'm using the following code: 我正在使用以下代码:
with open("test_out.txt", "wt") as outfile:
with open("test_in.txt", "rt") as infile:
for line in infile:
line.split(";")
outfile.write(line)
Can't seem to get it to work. 似乎无法使其正常工作。 I've tried "if" statements as well, but I'm definitely missing something. 我也尝试过“ if”语句,但是我肯定缺少一些东西。
Any help would be greatly appreciated! 任何帮助将不胜感激!
line.split(";")
returns the different words of your line, it does not modify line
in place, so you need to write each returned word: line.split(";")
返回行中的不同单词,它不会修改line
,因此您需要编写每个返回的单词:
for word in line.split(";"):
outfile.write(word)
Alternatively, you just replace all ;
或者,您只需替换所有;
characters by \\n
, for instance with: \\n
字符,例如:
outfile.write(infile.read().replace(';', '\n'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.