您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python-从子目录中找不到的目录文件中读取文件

Python-从子目录中找不到的目录文件中读取文件

正如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
python 2022/1/1 18:46:15 有307人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶