首页 > 解决方案 > 计算文件中句子单词重复的次数

问题描述

我想检查一个单词在文件中重复了多少次。我已经看到其他代码在文件中查找单词,但它们不能解决我的问题。从这里我的意思是如果我想找到“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()

标签: pythonlistdictionaryfile-handling

解决方案


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

如果是这种情况,您可以尝试以下方法:

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”是不同的词)。为了使其不区分大小写,您可以file_data在与小写比较的过程中使用str.lower().

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 ...(context-manager),这样文件会自动关闭。

  2. Python 字符串(以及列表、元组等)具有.count(what)方法。它返回what在对象中找到的出现次数。

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

  4. 未完待续


推荐阅读