簡體   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