【发布时间】:2017-09-05 21:17:05
【问题描述】:
我只是想知道一个小脚本或内置函数,它可以读取文本语料库并在解析过程中遇到逗号时用新行写入。
hello,world,rick,and,morty should be
hello,
world,
rick,
and,
morty
【问题讨论】:
标签: python string file io formatting
我只是想知道一个小脚本或内置函数,它可以读取文本语料库并在解析过程中遇到逗号时用新行写入。
hello,world,rick,and,morty should be
hello,
world,
rick,
and,
morty
【问题讨论】:
标签: python string file io formatting
不确定您的读写过程的实现,但您可以轻松地将逗号替换为逗号+换行符:
line = line.replace(',',',\n')
读取位可能是这样的:
with open('filetoread.txt', r) as f:
for line in f.readlines():
line = line.replace(',',',\n')
# ...now write these to a file or print the lines, etc.
【讨论】:
您可以通过以下方式完成这项工作:
f = open('filename', 'r+')
n = f.read().replace(',', ',\n') # do the job!
f.truncate(0) # remove file contents from begin
f.write(n) # write result into file :)
f.close()
【讨论】: