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

标签 python split newline counter

我正在尝试将文本文件拆分为单词,\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/

相关文章:

python - 解析和使用 .properties 文件中使用 PYTHON 定义的属性

mysql - 根据表中的值将 MySQL 行拆分为多行

git 确保每个文件末尾有换行符

go - 带字符串的奇怪行为.TrimSuffix\n

python - Pandas read_excel 返回对象类型的列

python - Keras 使用顺序层添加数据

python - 你如何计算文件夹中的子目录?

string - 如何使用CMD拆分字符串

Python:按模式分割字符串

C编程: How to prevent printf statement from printing out new line values?