我的代码有问题。我有一个文本文件,该文本文件内部有一千个来自句子的制表符/下一行单词。我的问题是我想恢复此文本文件中的单词并再次使其成为一个句子。
我想到了一种方法,即制作一个 for 循环语句,如果它击中点.
,那么它将将该句子存储在列表中。
with('test','r') as f:
text = f.open()
sentence = []
sentences = []
for words in text:
if words != "."
sentence.append(words)
elif words == "."
sentence.append(words)
sentences.append(sentence)
sentence = []
#Sample output
#[['This', 'is', 'a', 'sentence', '.'], ['This', 'is', 'the', 'second', 'sentence', '.'],
#['This', 'is', 'the', 'third', 'sentence', '.']],
#This is the text file
This
is
a
sentence
.
This
is
the
second
sentence
.
This
is
thr
third
sentence
.
代码有点工作,但有点复杂。我发现了一个更短且不那么复杂的想法。预先感谢您。
最佳答案
这非常简单。从文件中读取,按句点拆分为行,用任意空格拆分每行,用单个空格重新连接行,将句点放回句子末尾。
sentences = [' '.join(x.split()) + '.' for x in open('test','r').read().split('.')]
关于python - 如何在 .txt 文件中的一组下一行单词中的点之后下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54648629/