1

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

4

4 回答 4

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)

在评论中的建议之后,这里是“优化”版本:

with open("text.txt", 'r') as oFile:
    lResults = [line.replace(" ", "\n") for line in oFile]

with open("results.txt", "w") as oFile:
    oFile.writelines(lResults)

编辑:对评论的回应:

嘿塞巴斯蒂安 - 我刚试过你的代码,它一直在输出文件中给我奇怪的字符!我做错了什么吗?– 弗雷迪 1 分钟前

你所说的“奇怪”字符是什么意思?您有非 ASCII 文件吗?对不起,但对我来说它工作得很好,我刚刚测试过。

在此处输入图像描述 在此处输入图像描述

于 2013-07-26T20:47:51.087 回答
2

尝试这个:

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

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

于 2013-07-26T20:45:26.100 回答
1

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

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文件而不是打印它:)(==> 片段已编辑)。


请参阅 pythonregex文档:

sub(pattern, repl, string, count=0, flags=0)
  • pattern: 搜索模式
  • repl:替换模式
  • string:要处理的字符串,在这种情况下,line

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

于 2013-07-26T20:50:27.667 回答
1
def (in_file, out_file):
  with open(in_file, 'r') as i, open(out_file, 'w') as o:
     w.write(i.read().replace(' ', os.linesep))

请注意,这既不循环也不写入'\n',而是os.linesep\nLinux 和\r\nWindows 等上。

另请注意,答案的最大部分来自alwaysprep,如果他从解决方案中取出循环,他应该得到它的功劳。(他真的删除了他的答案吗?再也找不到了。)

于 2013-07-26T21:13:03.723 回答