正如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