python - 如何在 .txt 文件中的一组下一行单词中的点之后下一行

标签 python

我的代码有问题。我有一个文本文件,该文本文件内部有一千个来自句子的制表符/下一行单词。我的问题是我想恢复此文本文件中的单词并再次使其成为一个句子。

我想到了一种方法,即制作一个 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/

相关文章:

python - 将 TensorFlow Checkpoint 部署到 Google Cloud Platform

python - 操作系统错误: [Errno 22] Invalid argument: (Read file from Github)

python - 在scrapy中并行运行1个网站的多个蜘蛛?

python - py 安装程序 numpy. EXE在运行时抛出错误

python:将 'backslash double-quote'字符串写入文件

javascript - 如何通过 Node JS 从 Python 调用并检索结果?

python - 使用 XOR 在 Python 中查找数组中缺失的数字

python - 使用实际数据时间和生日以及数据字段在 django 模板中定义年龄

python - 检查数组行是否为None并为其赋值

python - Tensorflow 1.6 中的 SSD_MOBILENET V1 到 TensorRT