[英]Markov Model Implementation in Python
我試圖在一組線上實現Markov屬性。 我需要以下單詞對應頻率的所有唯一單詞。
輸入項
文件名:Example.txt
I Love you
I Miss you
Miss you Baby
You are the best
I Miss you
代碼段
from collections import Counter
import pprint
class TextAnalyzer:
text_file = 'example.txt'
def __init__(self):
self.raw_data = ''
self.word_map = dict()
self.prepare_data()
self.analyze()
pprint.pprint(self.word_map)
def prepare_data(self):
with open(self.text_file, 'r') as example:
self.raw_data=example.read().replace('\n', ' ')
example.close()
def analyze(self):
words = self.raw_data.split()
word_pairs = [[words[i],words[i+1]] for i in range(len(words)-1)]
self.word_map = dict()
for word in list(set(words)):
for pair in word_pairs:
if word == pair[0]:
self.word_map.setdefault(word, []).append(pair[1])
self.word_map[word] = Counter(self.word_map[word]).most_common(11)
TextAnalyzer()
實際產量
{'Baby': ['You'],
'I': ['Love', 'Miss', 'Miss'],
'Love': ['you'],
'Miss': ['you', 'you', 'you'],
'You': ['are'],
'are': ['the'],
'best': ['I'],
'the': ['best'],
'you': [('I', 1), ('Miss', 1), ('Baby', 1)]}
預期產量:
{'Miss': [('you',3)],
'I': [('Love',1), ('Miss',2)],
'Love': ['you',1],
'Baby': ['You',1],
'You': ['are',1],
'are': ['the',1],
'best': ['I',1],
'the': ['best'],
'you': [('I', 1), ('Miss', 1), ('Baby', 1)]}
我希望根據最大頻率對輸出進行排序。 如何改善代碼以實現該輸出。
為了更接近您的預期結果,您可以編輯analize
方法:
def analyze(self):
words = self.raw_data.split()
word_pairs = [[words[i],words[i+1]] for i in range(len(words)-1)]
self.word_map = dict()
for word in list(set(words)):
pairword = []
for pair in word_pairs:
if word == pair[0]:
pairword.append(pair[1])
self.word_map[word] = Counter(pairword).most_common()
打印:
{'Baby': [('You', 1)],
'I': [('Miss', 2), ('Love', 1)],
'Love': [('you', 1)],
'Miss': [('you', 3)],
'You': [('are', 1)],
'are': [('the', 1)],
'best': [('I', 1)],
'the': [('best', 1)],
'you': [('I', 1), ('Miss', 1), ('Baby', 1)]}
這是您想要的但未排序的。 您需要編寫一種自定義打印方法來為您進行排序。
例如,向類添加以下方法:
def printfreq(self):
sortkeys = sorted(self.word_map, key=lambda k:max(self.word_map[k], key=lambda val:val[1], default=(None, 0))[1], reverse=True)
for kk in sortkeys:
pprint.pprint(f"{kk} : {self.word_map[kk]}")
並將行pprint.pprint(self.word_map)
替換為self.printfreq()
導致打印:
"Miss : [('you', 3)]"
"I : [('Miss', 2), ('Love', 1)]"
"you : [('I', 1), ('Miss', 1), ('Baby', 1)]"
"Love : [('you', 1)]"
"the : [('best', 1)]"
"You : [('are', 1)]"
"best : [('I', 1)]"
"Baby : [('You', 1)]"
"are : [('the', 1)]"
長排序鍵允許按列表中的最大頻率對字典鍵進行排序。
我在max
添加了默認參數。 這樣可以避免ValueError: max() arg is an empty sequence
,如果輸入中有一個或多個非重復的單詞,則可能會出現ValueError: max() arg is an empty sequence
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.