【问题标题】:Python - reading files from directory file not found in subdirectory (which is there)Python - 从子目录中找不到的目录文件中读取文件(在那里)
【发布时间】:2013-03-12 22:07:39
【问题描述】:

我确信这只是句法上的东西 - 但是我不知道为什么我的代码:

import os
from collections import Counter
d = {}
for filename in os.listdir('testfilefolder'):
    f = open(filename,'r')
    d = (f.read()).lower()
    freqs = Counter(d)
    print(freqs)

不起作用 - 它显然可以看到“testfilefolder”文件夹并告诉我文件在那里,即找不到错误消息“file2.txt”。所以它可以找到它告诉我它没有找到...

然而,我让这段代码工作:

from collections import Counter
d = {}
f = open("testfilefolder/file2.txt",'r')
d = (f.read()).lower()
freqs = Counter(d)
print(freqs)

奖金 - 这是做我想做的事情的好方法(从文件中读取并计算单词的频率)吗?这是我接触 Python 的第一天(虽然我有一些编程经验。)

不得不说我喜欢Python!

谢谢,

布赖恩

【问题讨论】:

    标签: python file-processing


    【解决方案1】:

    正如isedev 指出的,listdir() 只返回文件名,而不是完整路径(或相对路径)。解决这个问题的另一种方法是os.chdir()进入有问题的目录,然后os.listdir('.')

    其次,您的目标似乎是计算单词的频率,而不是字母(字符)。为此,您需要将文件的内容分解为单词。我更喜欢为此使用正则表达式。

    第三,您的解决方案分别计算每个文件的词频。如果您需要对所有文件执行此操作,请在开始时创建一个 Counter() 对象,然后调用 update() 方法来统计计数。

    事不宜迟,我的解决方案:

    import collections
    import re
    import os
    
    all_files_frequency = collections.Counter()
    
    previous_dir = os.getcwd()
    os.chdir('testfilefolder')
    for filename in os.listdir('.'):
        with open(filename) as f:
            file_contents = f.read().lower()
    
        words = re.findall(r"[a-zA-Z0-9']+", file_contents) # Breaks up into words
        frequency = collections.Counter(words)              # For this file only
        all_files_frequency.update(words)                   # For all files
        print(frequency)
    
    os.chdir(previous_dir)
    
    print ''
    print all_files_frequency
    

    【讨论】:

    • 非常感谢大家!我现在看到了 os.listdir 的问题,实际上它只是找到了名称而不是访问整个文件。 @Hai,我很欣赏你写的解决方案。我遇到了它似乎加载以及计算临时的问题?归档到计数中。因此,例如 file3.txt~ 在下面的输出中: file2.txt~ Counter({'e': 2, 'a': 1, 'c': 1, 'd': 1, 'i' : 1, 'l': 1, 's': 1}) file2.txt Counter({'a': 1, 'b': 1}) 目录中的所有文件都会发生这种情况 - 然后最后,它也会对它们进行计数。谢谢,布赖恩
    【解决方案2】:

    变化:

    f = open(filename,'r')
    

    收件人:

    f = open(os.path.join('testfilefolder',filename),'r')
    

    这实际上是你正在做的事情:

    f = open("testfilefolder/file2.txt",'r')
    

    原因:您列出了“testfilefolder”(当前目录的子目录)中的文件,但随后尝试在当前目录中打开文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-10
      • 1970-01-01
      • 2015-02-19
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      相关资源
      最近更新 更多