lResults = list()
with open("text.txt", 'r') as oFile:
for line in oFile:
sNewLine = line.replace(" ", "\n")
lResults.append(sNewLine)
with open("results.txt", "w") as oFile:
for line in lResults:
oFile.write(line)
以下是评论中建议后的“优化”版本:
^{pr2}$
编辑:回复评论:
hey sebastian - I just tried your code, it keeps giving me the weird
characters in the output file! am i doing something wrong with it? –
Freddy 1 min ago
import re
with open('thefile.txt') as f, open('out.txt', 'w') as out:
for line in f:
new_line = re.sub('\s', '\n', line)
# print new_line
out.write(new_line)
给你:
以下是评论中建议后的“优化”版本:
^{pr2}$编辑:回复评论:
你所说的“怪异”人物是什么意思?你有非ASCII文件吗? 抱歉,但对我来说它工作得很好,我只是测试了一下。在
您可以使用正则表达式来实现这一点:
您可能需要将
new_line
写回一个文件,而不是打印它:)(==>;代码段已编辑)。在请参阅python^{} 文档:
^{pr2}$pattern
:搜索模式repl
:替换模式string
:要处理的字符串,在本例中,line
注意:如果只想替换出现在行尾的空白,请使用
\s$
搜索模式,其中$
代表字符串的结尾(因此读作“字符串末尾的空格”)。如果确实需要替换每个空格,那么replace
方法str
就足够了。在试试这个:
现在,上面的“要处理的文本”将来自您之前在字符串中读取的输入文本文件-有关如何执行此操作的详细信息,请参见answer。在
相关问题 更多 >
编程相关推荐