编程语言
首页 > 编程语言> > Python – 从子目录中找不到目录文件中的文件(在那里)

Python – 从子目录中找不到目录文件中的文件(在那里)

作者:互联网

我确信它只是语法 – 我无法弄清楚为什么我的代码:

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的第一天(虽然我有一些编程exp.)

我不得不说我喜欢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

标签:multiple-files,file-processing,python
来源: https://codeday.me/bug/20190725/1535110.html