python-3.x - 如何使用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.
使用拆分功能后如何只打印一个单词?我很高兴我仍然需要改进这段代码。
任何帮助,将不胜感激。提前致谢。
解决方案
这是你的代码:
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)
推荐阅读
- node.js - 如何无限填充 mongoDB 模型?
- c# - log4net 没有写入两个 RollingFileAppenders
- spring - 使用 Spring WebClient 解码内容编码 gzip
- java - Why is deletion of an item at end of Dynamic array O(n) time complexity?
- angular - 无法使用选项卡式页面上的提供程序在 Angular 和 Ionic 中查询数据库
- google-apps-script - 从 Google 表格中获取项目列表
- django - 在 Django 模板中连接字符串和 UUID
- aem - 如何在aem中显示当前页面的父页面的每个子页面?
- python - 理解列表推导(和嵌套 LC)的语法
- javascript - 为什么 css 选择器会重复?(SCSS)