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

I am convinced it is something simply syntactic - I however can not figure out why my code:

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)

will not work - it apparently can see in to the 'testfilefolder' folder and tell me that the the file is there i.e. an error message 'file2.txt' is not found. So it can find it to tell me that it is not found...

I however get this piece of code to work:

from collections import Counter

d = {}

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

d = (f.read()).lower()

freqs = Counter(d)

print(freqs)

Bonus - is this a good way of doing what I am trying to do (read from file and count the frequencies of words)? This is my first day with Python (although I have some amounts of programming exp.)

I have to say that I am liking Python!

Thanks,

Brian

解决方案

As isedev pointed out, listdir() returns just the file names, not the full path (or relative paths). Another way to deal with this problem is to os.chdir() into the directory in question, then os.listdir('.').

Secondly, it seems your goal is to count frequency of words, not letters (characters). For that, you will need to break up the contents of the files into words. I prefer to use regular expression for this.

Thirdly, your solution counts words frequencies for each files separately. If you ever need to do it for all files, create a Counter() object in the beginning, then call the update() method to tally the counts.

Without further ado, my solution:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值