簡體   English   中英

如何在python中編寫字母bigram(aa,ab,bc,cd…zz)頻率分析計數器?

[英]How to write a alphabet bigram (aa, ab, bc, cd … zz) frequency analysis counter in python?

這是我當前的代碼,它打印出輸入文件中每個字符的頻率。

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)的雙字母組的頻率,而不要打印標點符號。 這個怎么做?

您可以圍繞當前代碼進行構建以處理對。 通過添加另一個變量來跟蹤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

(免責聲明:我的系統上沒有python2。如果代碼中存在問題,請通知我。)

有一種更有效的方法來統計二部圖:使用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:]))

如果您使用的是nltk

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

[OUT]:

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

進行計數:

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

如果您想要python本機解決方案,請查看:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM