gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:33:18 25 4
gpt4 key购买 nike

我是 python 的新手,正在尝试制作马尔可夫链。其他示例显示了对象实例的用法,而我还没有走那么远。我还没有完成值部分的随机选择,但基本上到目前为止我对这段代码的输出感到茫然。

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)

输出:

Lindsays-MBP:markov lindsayg$ python markov.py 
{('a', 'fox?'): [], ('Sam', 'I'): ['am?'], **('you,', 'could'): ['you', 'you', 'you', 'you', 'you', 'yo**u']**, ('could', 'you'): ['in', 'with', 'in', 'with'], ('you', 'with'): [], ('box?', 'Would'): [], ('ham?', 'Would'): [], ('I', 'am?'): [], ('you', 'in'): ['a', 'a', 'a', 'a'], ('a', 'house?'): [], ('like', 'green'): ['eggs'], ('like', 'them,'): ['Sam'], ('and', 'ham?'): [], ('Would', 'you'): ['like', 'like'], ('a', 'mouse?'): [], ('them,', 'Sam'): ['I'], ('in', 'a'): ['house?', 'box?'], ('with', 'a'): ['mouse?', 'fox?'], ('house?', 'Would'): [], ('a', 'box?'): [], ('Would', 'you,'): ['could', 'could', 'could', 'could'], ('green', 'eggs'): ['and'], ('you', 'like'): ['green', 'them,'], ('mouse?', 'Would'): [], ('fox?', 'Would'): [], ('eggs', 'and'): ['ham?']}

一个奇怪的输出示例(应该只有 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?

最佳答案

您的问题是您查找单词索引的方式:index举一例。有 6 个 'you'(和 4 个不同的 'you,'),每个都将获得相同的索引 word_number = 3 , 所以它们都将被添加到 ('Would', 'you,') 对中。

要获取索引,您应该使用内置的 enumerate :

for word_number, word in enumerate(file_list):
...

关于python - Python 中的马尔可夫链(初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29654792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com