我的代码有问题。我有一个文本文件,并且在此文本文件中是一千个来自句子的带标签的/下一行的单词。我的问题是我想还原此文本文件中的单词,然后再次使其成为句子。
我想过一种制作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('.')]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句