gpt4 book ai didi

python - 如何检查列表中的单词然后返回计数?

转载 作者:行者123 更新时间:2023-12-01 04:50:44 25 4
gpt4 key购买 nike

我对 python 比较陌生,有一个问题:

我正在尝试编写一个脚本,该脚本将读取 .txt 文件并检查单词是否在我提供的列表中,然后返回该列表中有多少单词的计数。

到目前为止,

import string
#this is just an example of a list
list = ['hi', 'how', 'are', 'you']

filename="hi.txt"
infile=open(filename, "r")
lines = infile.readlines()
for line in lines:
words = line.split()
for word in words:
word = word.strip(string.punctuation)

我尝试将文件拆分为行,然后将行拆分为不带标点符号的单词。

我不知道此后该去哪里。我希望最终的输出是这样的:

"your file has x words that are in the list".

谢谢!

最佳答案

您可以使用以下命令将文件拆分为单词:

words=reduce(lambda x,y:x+y,[line.split() for line in f])

然后通过循环并使用 count 函数来计算单词列表中的单词数:

w_list = ['hi', 'how', 'are', 'you']
with open("hi.txt", "r") as f :
words=reduce(lambda x,y:x+y,[line.split() for line in f])
for w in w_list:
print "your file has {} {}".format(words.count(w),w)

关于python - 如何检查列表中的单词然后返回计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28546584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com