gpt4 book ai didi

Python 拆分文本文件并保留换行符

转载 作者:太空宇宙 更新时间:2023-11-03 15:05:02 24 4
gpt4 key购买 nike

我正在尝试将文本文件拆分为单词,\n 被算作一个单词。

我的输入是这个文本文件:

War and Peace

by Leo Tolstoy/Tolstoi

我想要这样的列表输出:

['War','and','Peace','\n','\n','by','Leo','Tolstoy/Tolstoi']

使用 .split() 我得到这个:

['War', 'and', 'Peace\n\nby', 'Leo', 'Tolstoy/Tolstoi']

所以我开始写一个程序把\n作为一个单独的条目放在单词后面,代码如下:

for oldword in text:
counter = 0
newword = oldword
while "\n" in newword:
newword = newword.replace("\n","",1)
counter += 1

text[text.index(oldword)] = newword

while counter > 0:
text.insert(text.index(newword)+1, "\n")
counter -= 1

但是,程序似乎在 counter -= 1 行挂起,我想不通为什么。

注意:我意识到如果这可行,结果将是 ['Peaceby',"\n","\n"];这是一个不同的问题,以后要解决。

最佳答案

你不需要这么复杂的方法,你可以简单地使用正则表达式和re.findall()来找到所有的单词和换行:

>>> s="""War and Peace
...
... by Leo Tolstoy/Tolstoi"""
>>>
>>> re.findall(r'\S+|\n',s)
['War', 'and', 'Peace', '\n', '\n', 'by', 'Leo', 'Tolstoy/Tolstoi']

'\S+|\n' 将匹配长度为 1 或更多的非空白字符的所有组合 (\S+) 或新行 (\n).

如果您想从文件中获取文本,您可以执行以下操作:

with open('file_name') as f:
re.findall(r'\S+|\n',f.read())

阅读有关正则表达式的更多信息 http://www.regular-expressions.info/

关于Python 拆分文本文件并保留换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33846797/

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