首页 > 解决方案 > Python 中的马尔可夫模型实现

问题描述

我正在尝试在一组行上实现马尔可夫属性。我需要沿着以下单词的相应频率的所有唯一单词。

例子

输入
文件名: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)]}

我希望根据最大频率对输出进行排序。如何改进我的代码以实现该输出。

标签: pythonnlp

解决方案


为了更接近您的预期结果,您可以编辑该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如果输入中有一个或多个非重复单词可能出现的情况。


推荐阅读