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

Python splitting text file keeping newlines

我正在尝试将文本文件拆分为单词,\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"];那是以后要解决的不同问题。

为了摆脱两个 \n 字符并成功拆分 spaces 以使列表的每个索引成为不同的词,您可以首先替换 [=11 的值=] 与单个 space...string.replace('\n\n', ' ') 并将其等同于一个新字符串,然后按 spaces...newString.split(' ')

拆分

你不需要这么复杂的方法,你可以简单地使用正则表达式和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' 将匹配所有 none 长度为 1 或以上的空白字符 (\S+) 或换行 (\n).

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

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

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

当您阅读文件时,您可以逐行处理,这样您就可以一次拆分一行并适当地处理换行符:

>>> [word for line in inputFile for word in line.rstrip('\n').split() + ['\n']]
['War', 'and', 'Peace', '\n', '\n', 'by', 'Leo', 'Tolstoy/Tolstoi', '\n']

简单分解:

  • for line in inputFile:对于输入文件中的每一行
  • for word in line.rstrip('\n').split() + ['\n']: 剥离换行符并拆分行,将新行作为单独的元素重新添加

如前所述,如果您使用不带分隔符的 split(),那么您实际上并不需要 rstrip('\n')

您可以将这些确切的表达式用作循环而不是列表理解:

result = []
for line in inputFile:
    for word in line.rstrip('\n').split():
        result.append(word)
    result.append('\n')
print(result)

给出相同的输出:

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

这是另一个变体:

with open('data.txt') as fobj:
    for line in fobj:
        words.extend(line.split())
        words.append('\n')

它在包括制表符在内的所有空格处拆分单词。