gpt4 book ai didi

python - 在 Python 中删除不必要的换行符的最有效方法

转载 作者:太空狗 更新时间:2023-10-29 21:02:59 30 4
gpt4 key购买 nike

我正在寻找如何使用 Python 去除文本中不必要的换行符,就像您从 Project Gutenberg 中得到的一样,他们的纯文本文件每 70 个字符左右换行一次。在 Tcl 中,我可以做一个简单的 string map,像这样:

set newtext [string map "{\r} {} {\n\n} {\n\n} {\n\t} {\n\t} {\n} { }" $oldtext]

这将使由两个换行符(或一个换行符和一个制表符)分隔的段落分开,但将以单个换行符(替换空格)结尾的行放在一起,并删除多余的 CR。由于 Python 没有string map,我还没有找到最有效的方法来转储所有不需要的换行符,虽然我很确定它不是 只是为了按顺序搜索每个换行符并将其替换为空格。如果一切都失败了,我可以只评估 Python 中的 Tcl 表达式,但我想找出最好的 Pythonic 方法来做同样的事情。这里有 Python 行家可以帮我吗?

最佳答案

与 tcl string map 最接近的等效项是 str.translate , 但不幸的是它只能映射单个字符。因此,有必要使用正则表达式来获得类似的紧凑示例。这可以通过 look-behind/look-ahead assertions 来完成,但必须先替换 \r:

import re

oldtext = """\
This would keep paragraphs separated.
This would keep paragraphs separated.

This would keep paragraphs separated.
\tThis would keep paragraphs separated.

\rWhen, in the course
of human events,
it becomes necessary
\rfor one people
"""

newtext = re.sub(r'(?<!\n)\n(?![\n\t])', ' ', oldtext.replace('\r', ''))

输出:

This would keep paragraphs separated. This would keep paragraphs separated.

This would keep paragraphs separated.
This would keep paragraphs separated.

When, in the course of human events, it becomes necessary for one people

不过,我怀疑这是否与 tcl 代码一样高效。

更新:

我用这个 Project Gutenberg EBook of War and Peace 做了一点测试(纯文本 UTF-8,3.1 MB)。这是我的 tcl 脚本:

set fp [open "gutenberg.txt" r]
set oldtext [read $fp]
close $fp

set newtext [string map "{\r} {} {\n\n} {\n\n} {\n\t} {\n\t} {\n} { }" $oldtext]

puts $newtext

和我的 python 等价物:

import re

with open('gutenberg.txt') as stream:
oldtext = stream.read()

newtext = re.sub(r'(?<!\n)\n(?![\n\t])', ' ', oldtext.replace('\r', ''))

print(newtext)

粗略的性能测试:

$ /usr/bin/time -f '%E' tclsh gutenberg.tcl > output1.txt
0:00.18
$ /usr/bin/time -f '%E' python gutenberg.py > output2.txt
0:00.30

所以,不出所料,tcl 版本效率更高。然而,python 版本的输出似乎更清晰(没有在行首插入额外的空格)。

关于python - 在 Python 中删除不必要的换行符的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36242061/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com