处理字典中列出的文件

2024-10-01 11:41:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文档topics.txt

1~cocoa
2~
3~
4~
5~grain~wheat~corn~barley~oat~sorghum
6~veg-oil~linseed~lin-oil~soy-oil~sun-oil~soybean~oilseed~corn~sunseed~grain~sorghum~wheat
7~
8~
9~earn
10~acq
11~earn
12~earn~acq
13~earn
14~earn

...

其中每行开头的数字是一个文件名。你知道吗

我有大约20000个文件要分类。 到目前为止,我已经为每个单词创建了字典,字典的元素是相应的文件名, 例如:('earn'、['9'、'11'、'12'、'13'、'14'、'18'、'23'、'24'、'27'、'36'、'37'、'38'……等等) 现在我需要计算earn中的单词总数,即属于earn的所有文件,这些文件都存在于目录d:/单个单词中

我需要我的输出是这样的: 字数,总字数

“赚”,30000

“谷物”,40000

import os
import re
import sys
from collections import Counter
from glob import glob

sys.stdout=open('f1.txt','w')

def removegarbage(text):
    text=re.sub(r'\W+',' ',text)
    text=text.lower()
    return text

folderpath='d:/individual-articles'
counter=Counter()

filepaths = glob(os.path.join(folderpath,'*.txt'))

with open('topics.txt','r') as filehandle:
    d = collections.defaultdict(list)
    for line in f:
        value, *keys = line.strip().split('~')
        for key in filter(None, keys):
            d[key].append(value)

for i in d.items():
    for filepath in filepaths:
        with open(filepath,'r') as filehandle:
            lines = filehandle.read()
            words = removegarbage(lines).split()
            counter.update(words)
    print(counter)

到目前为止,我的程序在文件列表中运行良好,但是如何获得文件列表中每个单词的总字数?上面的代码不起作用!你知道吗


Tags: 文件textinimporttxtforcounteropen
1条回答
网友
1楼 · 发布于 2024-10-01 11:41:03

如何计算给定文件列表中的字数?

def count_words(files):
  path = './' # check that this path is correct
  return sum(len(open(path + str(f) +'.txt').read().split()) for f in files)

那么如何对d中的每个条目求和?

total = sum(count_words(d[k]) for k in d)

相关问题 更多 >