python - 我做了一个程序来检查文件中是否有一个词,需要一些建议

标签 python

我想打印这个词是否出现,以及这个词在文件中出现了多少次。除了这个词在文件中出现 1 次或 0 次之外,我无法说出任何其他内容。

这个问题出现在第26行,print("It appears "+ str(wordcount[word]) + "times")

特别是 str(wordcount[word])。这可能是一个简单的问题,但这是我使用 Python 的第一周,所以如果有人有想法请分享。谢谢!

我试过放置 wordcount[word]word_counter.__getitem__(wordcount[word])word_counter.__getitem__(wordcount)

import collections
file = open(r"C:\Users\Patrick Wu\Documents\1wordfreqtest.txt", "r")
if file.mode == "r":
    contents = file.read()
word = input("Word to check for :")
wordcount = {}
"""this below is to remove difference between upper and lower cases as 
well as punctuation""" 
for word in contents.lower().split():
    word = word.replace(".","")
    word = word.replace(",","")
    word = word.replace(":","")
    word = word.replace("\"","")
    word = word.replace("!","")
    word = word.replace("“","")
    word = word.replace("‘","")
    word = word.replace("*","")
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1

word_counter = collections.Counter(wordcount)
if word in str(contents):
    print("This word is in the file :)")
    print("It appears " + str(wordcount[word]) + " times")
else:
    print("This word isn't in the file")

最佳答案

变量 word 在局部范围内被循环覆盖。所以你输入的 word 被循环覆盖,你最终检查了输入文件最后一个单词的计数。将输入词更改为与您在文件中循环访问的词不同的变量名。

关于python - 我做了一个程序来检查文件中是否有一个词,需要一些建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57117028/

相关文章:

python - Python 中的 __builtin__ 模块

python - 计算字符串中最大连续 "a"的数量。 python 3

python - 对于 Django 模板 {%url%} 标记,如何从通用 View 上下文中查找所有 URL 参数,而不仅仅是最后一个?

python - 找不到服务 "taskqueue"的 api 代理

python - python 中接收用户输入并返回总和和平方的函数

javascript - Python Flask + Angular 错误 : 'StoreController Undefined'

python - 使用Python的OpenCV-将帽子的图像放置在网络摄像头源的头部

Python 正则表达式 - 查找子字符串中的多个字符

python - 在种子中生成随机数

Python 检查 int 是否在列表的某个对象中