当前位置:   article > 正文

python马尔可夫链_Python中的马尔可夫链(初学者)

python markov跳

我是python的新手,正在尝试构造markov链。其他的例子展示了对象实例的用法,我还没有走那么远。我还没有做随机选择的价值部分,但基本上,我对我的输出这段代码到目前为止的损失。在filename = open("dr-suess.txt")

def make_list(filename):

"""make file a list and a list of tuple tup_pairs"""

file_string = filename.read() #read whole file

file_list = file_string.split() #split on whitespace (not worrying about

# puncuation right now)

tup_pairs = []

for i in range(len(file_list)-1):

tup_pairs.append((file_list[i], file_list[i+1])) #making my tuple pair list

return tup_pairs, file_list

def mapping(filename):

tup_pairs, file_list = make_list(filename)

dictionary = {}

for pair in tup_pairs:

dictionary[pair] = [] #setting the value of dict to empty list

tup_pairs = set(tup_pairs) #throwing out repeated tuples

for word in file_list:

word_number = file_list.index(word) #index number of iter word

if word_number > 1: #because there is no -2/-1 index

compared_tuple = (file_list[word_number-2], file_list[word_number-1]) #to find

#preceeding pair to compare

for pair in tup_pairs:

if compared_tuple == pair:

dictionary[pair].append(word) #should append the word to my dict value (list)

print dictionary #getting weird results (some words should appear that dont, some

# don't appear that should)

mapping(filename)

输出:

^{pr2}$

奇怪输出的一个示例(应该只有4个“you”值,有6个):('you,', 'could'): ['you', 'you', 'you', 'you', 'you', 'you']

正在使用的fyi文件文本:Would you, could you in a house?

Would you, could you with a mouse?

Would you, could you in a box?

Would you, could you with a fox?

Would you like green eggs and ham?

Would you like them, Sam I am?

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号