【问题标题】:Loop through multiple txt files and count frequencies of chosen word in Python循环遍历多个 txt 文件并计算 Python 中所选单词的频率
【发布时间】:2021-02-07 22:19:14
【问题描述】:

我有一个练习题,要求我编写一个函数,该函数循环遍历 50 个文本文件并计算每个文本文件中所选单词的频率。我目前的代码如下所示:

def count(term):
    frequencies = 0
    
    work_dir = "C:/my_work_directory"
    for i in range(1, 51):
        name = "chapter-{i}.txt".format(i=i)
        path = os.path.join(work_dir, name)
        with io.open(path, "r") as fd:
            content = fd.read()
    
        chapter = io.StringIO(content)
        line = chapter.readline()
        print(chapter)
        while line:
            lower = line.lower()
            cleaned = re.sub('[^a-z ]','', lower)
            words = cleaned.strip().split(' ')
            for word in words:
                if word == term:
                    frequencies += 1
            line = chapter.readline()
        
        print(frequencies)

我想要的输出是,如果我输入 count("Man"),我会得到 50 个不同频率的单词“Man”在每个文本文件中出现的频率。但是,我目前得到的只是 50 个零。我相当确定这是因为我已将变量“频率”初始化为 0,然后没有对其进行任何操作。谁能帮我解决这个问题或告诉我哪里出错了?任何帮助将不胜感激,谢谢。

【问题讨论】:

标签: python text-files word-frequency


【解决方案1】:

嗯,你的“Man”有一个大写字母,而且你所有的单词都是小写的。所以第一件事是在term 变量上调用lower() 函数。第二件事是错误的,您稍后才会注意到,您正在保持运行计数,而不是每个文件的计数。所以将频率变量的初始化移到for循环中。所以它应该看起来像这样。

def count(term):
    term = term.lower()
    
    work_dir = "C:/my_work_directory"
    for i in range(1, 51):
        frequencies = 0

        name = "chapter-{i}.txt".format(i=i)
        path = os.path.join(work_dir, name)
        with io.open(path, "r") as fd:
            content = fd.read()
    
        chapter = io.StringIO(content)
        line = chapter.readline()
        print(chapter)
        while line:
            lower = line.lower()
            cleaned = re.sub('[^a-z ]','', lower)
            words = cleaned.strip().split(' ')
            for word in words:
                if word == term:
                    frequencies += 1
            line = chapter.readline()
        
        print(frequencies)

【讨论】:

    【解决方案2】:

    我运行了它,并且在我更改 work_dir="" 后它运行良好(所以它查看了本地)。所以我认为你应该检查工作目录路径或断言术语参数是否正确

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-24
      • 2015-06-14
      • 1970-01-01
      • 2017-04-03
      • 2021-12-09
      • 1970-01-01
      • 2013-09-10
      • 2015-01-07
      相关资源
      最近更新 更多