【问题标题】:Finding and counting the frequency of known pairs of words in multiple files [closed]查找和计算多个文件中已知单词对的频率[关闭]
【发布时间】:2013-06-05 06:30:27
【问题描述】:

基本上我需要计算多个文件中单词对的数量。我在一个名为result.txt 的文件中有一个单词对列表,它看起来像:

  1. 作者
  2. 他们是
  3. 分组

我想检查位于给定目录中的许多文本文件中这些对的频率,并按降序打印对序列和相应的频率。输出必须是以下形式:

  1. 将他们的 205 分组
  2. 他们是 180
  3. 56 个

我已经尝试了以下方法:

import os
import re
from collections import Counter
from glob import iglob
from collections import defaultdict
import itertools as it

folderpath = 'path/to/directory'
pairs=defaultdict(int)

logfile = open('result.txt', 'r')
loglist = logfile.readlines()
logfile.close()
found = False
for line in loglist:
    for filepath in iglob(os.path.join(folderpath,'*.txt')):
        with open(filepath,'r') as filehandle:
            for pair in it.combinations(re.findall('\w+',line),2):
                pairs[tuple(pair)]+=1
    found=True                    
resultList=[pair+(occurences, ) for pair, occurences in pairs.iterkeys()]

但这并没有给我预期的结果。我将不胜感激!

【问题讨论】:

  • Aaaaan 问题 iiiis?
  • 为什么这里的 self 未定义?
  • 您希望self 是什么?
  • 这个问题显然是脑残的copypasta作业。
  • self 是否未定义?什么是回溯(完整的),即您遇到了什么错误?您似乎没有对 self 的单一引用。

标签: python string python-3.x sequence


【解决方案1】:

使用combinations() 时,您将获得所有对,甚至是不相邻的对。您可以创建一个返回相邻对的函数。我已经尝试了以下代码并且它有效,也许它可以给你一些见解:

import os
import re
from collections import Counter

def pairs(text):
    ans = re.findall(r'[A-Za-z]+', text)
    return (tuple(ans[i:i+2]) for i in xrange(len(ans)-1))

mypairs = tuple([ tuple(line.split()[-2:]) for line in open('results.txt')])

c = Counter()
folderpath = 'path/to/directory'
for dirpath, dnames, fnames in os.walk(folderpath):
    for f in fnames:
        if not '.txt' in f: continue
        for line in open(os.path.join(dirpath, f)):
            c += Counter(p for p in pairs(line) if p in mypairs)

for item in c.most_common():
    print item

【讨论】:

  • 我没有得到输出!for line in fileinput.input(iglob(os.path.join(folderpath, '*.txt'))) c += Counter(p for p in pairs(line) if p in mypairs),行不通,你能建议另一种选择吗?
  • @user2464521 我改成了os.walk,这样更容易理解,也很容易递归找到所有的“.txt”文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
  • 2023-03-22
  • 1970-01-01
  • 2015-06-14
相关资源
最近更新 更多