[英]Python - reading files from directory file not found in subdirectory (which is there)
我堅信這只是一種語法-但是我不知道為什么我的代碼:
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!
謝謝,
布賴恩
更改:
f = open(filename,'r')
至:
f = open(os.path.join('testfilefolder',filename),'r')
實際上,這是您在做什么:
f = open("testfilefolder/file2.txt",'r')
原因:您正在“ testfilefolder”(當前目錄的子目錄)中列出文件,但隨后嘗試在當前目錄中打開文件。
正如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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.