繁体   English   中英

检查单词在文本文件中出现的次数 (Python)

[英]Checking # of times word occurs in text file (Python)

我在 python 工作,试图找到在文本文件中找到输入的次数,但 output 始终显示文本文件的字母数,而不是单词在文件中出现的次数。 我不确定是什么导致它变成 output 字母计数。

def occurrenceChecker(query):
    wordInFile = 0 
    file = open("C:\Users\Noah\Desktop\1000words.txt") 
    documentText = file.read

    for query in documentText():
        wordInFile +=1
    
    if wordInFile == 0:
        print("Your argument occurred " + str(wordInFile) + " times, none.")
    if wordInFile >= 1 and wordInFile <= 5:
        print("Your argument occurred " + str(wordInFile) + " times, low.")
    if wordInFile >= 6 and wordInFile <= 10:
        print("Your argument occurred " + str(wordInFile) + " times, medium.")
    if wordInFile >=11:
        print("Your argument occurred " + str(wordInFile) + " times, high.")

Output:

Please enter an argument that you are searching for in the file: stuck
Your argument occurred 4875 times, high.
Your argument occurred 4875 times, high.

当您不想成为时,您正在呼叫 function,而当您想要成为时,您却没有呼叫 function。

for query in documentText(): for query in document_text:

document_text = file.read更改为document_text = file.read()

def occurrenceChecker(query):
    word_in_file = 0 
    file = open("C:\Users\Noah\Desktop\1000words.txt") 
    document_text = file.read()

    for query in document_text:
        word_in_file +=1
    
    if word_in_file == 0:
        print("Your argument occurred " + str(word_in_file) + " times, none.")
    if 1 <= word_in_file <= 5:
        print("Your argument occurred " + str(word_in_file) + " times, low.")
    if 6 <= word_in_file <= 10:
        print("Your argument occurred " + str(word_in_file) + " times, medium.")
    if word_in_file>=11:
        print("Your argument occurred " + str(word_in_file) + " times, high.")

既然你已经有了,我们现在需要解决递增的问题。 代替

for query in document_text:
        word_in_file +=1

你实际上想做这样的事情:

occurrences = document_text.count(query)

然后当然你应该有一个main()并在所述main()中调用你的 function

def main():
    occurrenceChecker(input())

if __name__ == "__main__":
    main()

资料来源: https://pythonexamples.org/python-count-occurrences-of-word-in-text-file/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM