超级简单的python程序用换行符代替空白?

2024-04-26 07:58:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python编写一个程序。 我想用新行替换txt文档中的空白。 我试过自己写,但是我的输出文件中充满了奇怪的字符。 你能帮忙吗? :)


Tags: 文件文档程序txt字符空白试图用
3条回答

给你:

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

你所说的“怪异”人物是什么意思?你有非ASCII文件吗? 抱歉,但对我来说它工作得很好,我只是测试了一下。在

enter image description hereenter image description here

您可以使用正则表达式来实现这一点:

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)

您可能需要将new_line写回一个文件,而不是打印它:)(==>;代码段已编辑)。在


请参阅python^{}文档:

^{pr2}$
  • pattern:搜索模式
  • repl:替换模式
  • string:要处理的字符串,在本例中,line

注意:如果只想替换出现在行尾的空白,请使用\s$搜索模式,其中$代表字符串的结尾(因此读作“字符串末尾的空格”)。如果确实需要替换每个空格,那么replace方法str就足够了。在

试试这个:

import re
s = 'the text to be processed'
re.sub(r'\s+', '\n', s)
=> 'the\ntext\nto\nbe\nprocessed'

现在,上面的“要处理的文本”将来自您之前在字符串中读取的输入文本文件-有关如何执行此操作的详细信息,请参见answer。在

相关问题 更多 >