【问题标题】:Calculating how many times sentence words are repeating in the file计算文件中句子单词重复的次数
【发布时间】:2026-02-15 08:10:02
【问题描述】:

我想检查一个单词在文件中重复了多少次。我已经看到了在文件中查找单词的其他代码,但它们不能解决我的问题。从这里我的意思是如果我想找到“Python 是我最喜欢的语言”程序将分割文本将告诉它重复了多少次文件。

def search_tand_export():
        file = open("mine.txt")
        #targetlist = list()
        #targetList = [line.rstrip() for line in open("mine.txt")]
        contentlist = file.read().split(" ")
        string=input("search box").split(" ")
        print(string)
        fre={}
        outputfile=open("outputfile.txt",'w')
        for word in contentlist:
            print(word)
            for i in string:
               # print(i)
                if i == word:
                    print(f"'{string}' is in text file ")
                    outputfile.write(word)
                    print(word)
    
                    spl=tuple(string.split())
                    for j in range(0,len(contentist)):
    
            
                        if spl in contentlist:
                            fre[spl]+=1 
                        else:
                            fre[spl]=1   
                        sor_list=sorted(fre.items(),key =lambda x:x[1])
                        for x,y in sor_list:
                            print(f"Word\tFrequency")
                            print(f"{x}\t{y}")
            else:
                continue
                
        print(f"The word or collection of word is not present")
    search_tand_export()

【问题讨论】:

    标签: python list dictionary file-handling


    【解决方案1】:

    试试这个脚本。它在file 中找到word,并计算在words 中找到它的次数:

    file = open('hello.txt','r')
    word = 'Python'
    words = 0
    for line in file:
      for word in line:
        words += 1
    print('File contains ' + word + ' ' + str(words) + ' times' )
    

    【讨论】:

    • 请注意,如果某些行多次包含该单词,则此代码不会计算该单词在句子中的所有出现次数,而只会计算该单词出现的行数。
    • 我很想使用这个脚本,但我搜索的不是一个词,而是用户输入的许多词。我想拆分单词并显示它们重复了多少次。
    【解决方案2】:

    我不太明白你想做什么。 但我想您正试图找出给定句子中的每个单词在文件中重复了多少次。

    如果是这样的话,你可以试试这样的:

    sentence = "Python is my favorite programming language"
    words = sentence.split()
    
    with open("file.txt") as fp:
        file_data = fp.read()
    
    for word in words:
        print(f"{file_data.count(word)} occurence(s) of '{word}' found")
    

    请注意,上面的代码区分大小写(即“Python”和“python”是不同的词)。为了使其不区分大小写,您可以使用str.lower()file_data 和比较期间的每个单词都带入小写。

    sentence = "Python is my favorite programming language"
    words = sentence.split()
    
    with open("file.txt") as fp:
        file_data = fp.read().lower()
    
    for word in words:
        print(f"{file_data.count(word.lower())} occurence(s) of '{word}' found")
    

    有几点需要注意:

    1. 您正在打开一个文件,甚至最终都没有关闭它(尽管您应该关闭它)。最好使用with open(...) as ...(上下文管理器),这样文件会自动关闭。

    2. Python 字符串(以及列表、元组等)具有.count(what) 方法。它返回在对象中找到了多少个what

    3. 了解 PEP-8 编码风格并为变量提供更好的名称。例如,很难理解fre 在您的代码中的含义。但是如果你把它命名为frequency,代码会变得更易读,也更容易使用。

    4. 待续

    【讨论】: