首页 > 解决方案 > 如何使用python在文本文档的每一行中打印不同的单词?

问题描述

我是 python 新手,我想从句子中打印不同的单词。下面是文本文件

Test.txt

1. As more than one social media historian has reminded few people, the Stonewall uprising was a rio-— more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Village’s 
Stonewall Inn, in the early morning of June 29, 1969.
2. As more than one social media historian has reminded majority people, the Stonewall uprising was a riot — more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Village’s Stonewall Inn, in the evening of July 12, 1979.

从上面的文本文件中,我想要从第一行开始的第 10 个单词(few)、第 11 个单词(people)、第 39 个单词(morning)、第 43 个单词(1969)。第二行还有第 10 个词(多数)、第 11 个词(人)、第 39 个词(晚上)、第 43 个(1979 年)。

注意:在 Test.txt 中 1. 表示第一行,2. 表示第 2 行

为此,我尝试使用拆分功能。

with open('Test.txt', 'r') as file:
for line in file:
    print (line.split('reminded',1)[1])

这是我得到的输出

few people, the Stonewall uprising was a riot - more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Villagers  Stonewall Inn, in the early morning of June 29, 1969.
majority people, the Stonewall uprising was a riot — more pointedly, a riot against police brutality, in response to an NYPD raid of Greenwich Village’s Stonewall Inn, in the evening of July 12, 1979.

使用拆分功能后如何只打印一个单词?我很高兴我仍然需要改进这段代码。

任何帮助,将不胜感激。提前致谢。

标签: python-3.x

解决方案


这是你的代码:


datalist = ['few','people','morning','1969','majority','people','evening','1979']
with open('file.txt', 'r') as file:
    data = file.read().replace('\n', ' ')

outputlist = data.replace('.','').split(" ")
for data in outputlist:
    if data in datalist:
        print(data)

推荐阅读