Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找和计算多个文件中已知单词对的频率_Python_String_Python 3.x_Sequence - Fatal编程技术网

Python 查找和计算多个文件中已知单词对的频率

Python 查找和计算多个文件中已知单词对的频率,python,string,python-3.x,sequence,Python,String,Python 3.x,Sequence,基本上,我需要计算多个文件中的单词对数量。我在一个名为result.txt的文件中有一个单词对列表,它看起来像: 的 路旁 是的 分组 我想检查位于给定目录中的许多文本文件中这些对的频率,并按降序打印对序列和相应的频率。输出的格式必须为: 他们的205组 他们是180岁 第56届会议 我已经尝试了以下方法: import os import re from collections import Counter from glob import iglob from collections imp

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

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

  • 他们的205组
  • 他们是180岁
  • 第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()]
    

    但这并没有给我预期的结果。我将感谢任何帮助

    使用
    组合()
    时,您将获得所有对,甚至是非相邻的对。您可以创建一个返回相邻对的函数。我尝试了以下代码,效果不错,也许它能给你一些启示:

    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
    

    Aaaaan问题IIIII S?为什么这里没有定义self?你期望self是什么?这个问题显然是脑死的。self没有定义吗?什么是回溯(完整的),即你得到了什么错误?您似乎没有一个对
    self
    的引用。我没有得到输出!对于fileinput.input(iglob(os.path.join(folderpath,*.txt'))中的行,c+=计数器(p表示成对的p(line),如果p表示成对的p),您能建议另一种选择吗?@user2464521我改为
    os.walk
    ,这非常容易理解,也很容易递归地找到所有的“.txt”文件