【问题标题】:How to write a alphabet bigram (aa, ab, bc, cd ... zz) frequency analysis counter in python?如何在python中编写一个字母二元组(aa,ab,bc,cd ... zz)频率分析计数器?
【发布时间】:2019-06-07 07:20:21
【问题描述】:

这是我当前的代码,它打印出输入文件中每个字符的频率。

from collections import defaultdict

counters = defaultdict(int)
with open("input.txt") as content_file:
   content = content_file.read()
   for char in content:
       counters[char] += 1

for letter in counters.keys():
    print letter, (round(counters[letter]*100.00/1234,3)) 

我希望它只打印字母 (aa,ab,ac ..zy,zz) 的二元组的频率,而不是标点符号。这个怎么做?

【问题讨论】:

标签: python nltk counter


【解决方案1】:

如果您使用的是nltk

from nltk import ngrams
list(ngrams('hello', n=2))

[出]:

[('h', 'e'), ('e', 'l'), ('l', 'l'), ('l', 'o')]

计数:

from collections import Counter
Counter(list(ngrams('hello', n=2)))

如果你想要一个 python 原生的解决方案,看看:

【讨论】:

    【解决方案2】:

    有一种更有效的计算二合图的方法:使用Counter。从阅读文本开始(假设它不是太大):

    from collections import Counter
    with open("input.txt") as content_file:
       content = content_file.read()
    

    过滤掉非字母:

    letters = list(filter(str.isalpha, content))
    

    您可能也应该将所有字母都转换为小写,但这取决于您:

    letters = letters.lower()    
    

    用自己构建一个剩余字母的 zip,移动一个位置,并计算双合字母:

    cntr = Counter(zip(letters, letters[1:]))
    

    规范化字典:

    total = len(cntr)
    {''.join(k): v / total for k,v in cntr.most_common()}
    #{'ow': 0.1111111111111111, 'He': 0.05555555555555555...}
    

    通过改变计数器,解决方案可以很容易地推广到三元组等:

    cntr = Counter(zip(letters, letters[1:], letters[2:]))
    

    【讨论】:

      【解决方案3】:

      您也可以围绕当前代码构建来处理对。通过添加另一个变量来跟踪 2 个字符而不是 1 个字符,并使用检查来消除非字母。

      from collections import defaultdict
      
      counters = defaultdict(int)
      paired_counters = defaultdict(int)
      with open("input.txt") as content_file:
         content = content_file.read()
         prev = '' #keeps track of last seen character
         for char in content:
             counters[char] += 1
             if prev and (prev+char).isalpha(): #checks for alphabets.
                 paired_counters[prev+char] += 1
             prev = char #assign current char to prev variable for next iteration
      
      for letter in counters.keys(): #you can iterate through both keys and value pairs from a dictionary instead using .items in python 3 or .iteritems in python 2.
          print letter, (round(counters[letter]*100.00/1234,3)) 
      
      for pairs,values in paired_counters.iteritems(): #Use .items in python 3. Im guessing this is python2.
          print pairs, values
      

      (免责声明:我的系统上没有 python 2。如果代码中有问题,请告诉我。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-04
        • 1970-01-01
        • 1970-01-01
        • 2011-08-18
        • 1970-01-01
        • 2011-01-15
        相关资源
        最近更新 更多