首页 > 解决方案 > 如何在 .txt 文件中的一组下一行单词中的一个点之后下一行

问题描述

我的代码有问题。我有一个文本文件,这个文本文件里面有一千个来自一个句子的标签/下一行单词。我的问题是我想恢复这个文本文件中的单词并再次使它成为一个句子。

我想到了一种方法,它是一个 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
.

代码有点工作,但有点复杂。我发现了一个更短且不那么复杂的想法。先感谢您。

标签: python

解决方案


以下是同一班轮,如果需要更多帮助,请告诉我:

sentences = open('test','r').read().split('\.')

推荐阅读