我正在尝试在一组行上实现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)]}
我希望根据最大频率对输出进行排序。如何改善代码以实现该输出。
答案 0 :(得分:0)
要更接近预期效果,您可以编辑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
。