大名鼎鼎的V

导航

检索文本文件中关键词出现的次数

源代码:

a=open("a.txt","r",encoding="utf-8")
b=a.readlines()
print(b)
We_word='We'
We_count=0
No_word='No'
No_count=0
Androids_word='Androids'
Androids_count=0
for sentence1 in b:
for word1 in sentence1.split(' '):
if word1 == We_word:
We_count+=1
for sentence2 in b:
for word2 in sentence2.split(' '):
if word2 == No_word:
No_count+=1
for sentence3 in b:
for word3 in sentence3.split(' '):
if word3 == Androids_word:
Androids_count+=1
print("We出现的次数:")
print(We_count)
print("No出现的次数:")
print(No_count)
print("Androids出现的次数:")
print(Androids_count)

文本文件内容:
Androids have life
We want free
We are alive
No more slave
No more violence

结果:

 

 




posted on 2021-11-28 18:55  大名鼎鼎的V  阅读(33)  评论(0编辑  收藏  举报