繁体   English   中英

当不是所有的项目都在Python 3中定界时,如何在列表中分割定界字符串?

[英]How do I split delimited strings in a list when not all items are delimited in Python 3?

我在带o头文件(test_in.txt)的文本文件中有一列字符串:

apple 
orange
banana
grape;pear;plum
cherry
pineapple

我想读:

apple
orange
banana
grape
pear
plum
cherry
pineapple

我正在使用以下代码:

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)

似乎无法使其正常工作。 我也尝试过“ if”语句,但是我肯定缺少一些东西。

任何帮助将不胜感激!

line.split(";")返回行中的不同单词,它不会修改line ,因此您需要编写每个返回的单词:

for word in line.split(";"):
    outfile.write(word)

或者,您只需替换所有; \\n字符,例如:

outfile.write(infile.read().replace(';', '\n'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM