gpt4 book ai didi

python - 添加到字典中键的值

转载 作者:行者123 更新时间:2023-12-01 04:33:05 24 4
gpt4 key购买 nike

我正在尝试用 python 制作马尔可夫链。目前,当我有诸如“Would you can”和“Would you like”之类的文本时,我的元组键 ('Would', 'you') 'could' 被 like 覆盖为 ('Would', 'you' ) 当我迭代我的文本文件时“喜欢”。

我正在尝试将键的每个新值添加到该键的值中。 IE。对于键 ('Would', 'you') 我希望值显示为 ('Would, 'you'): 'could', 'like'

这是我的代码:

def make_chains(corpus):
"""Takes an input text as a string and returns a dictionary of
markov chains."""
dict = {}
for line in corpus:
line = line.replace(',', "")
words = line.split()
words_copy = words
for word in range(0, len(words_copy)):
#print words[word], words[word + 1]
if dict[(words[word], words[word + 1])] in dict:
dict.update(words[word+2])
dict[(words[word], words[word + 1])] = words[word + 2]
#print dict
if word == len(words_copy) - 3:
break

return dict

最佳答案

简单的解决方案

简单的解决方案是使用collections.defaultdict:

from collections import defaultdict


def make_chains(input_list):
"""
Takes an input text as a list of strings and returns a dictionary of markov chains.
"""
chain = defaultdict(list)
for line in input_list:
line = line.replace(',', "")
words = line.split()
for i in range(0, len(words) - 2):
chain[words[i], words[i + 1]].append(words[i + 2])

return chain

有了这个你就得到:

$ print make_chains(["Would you like", "Would you could"])
defaultdict(<type 'list'>, {('Would', 'you'): ['like', 'could']})

修复原始内容

不过,为了让您更好地了解代码中出了什么问题,我们可以在不使用 defaultdict 的情况下修复原始解决方案。为此,需要提及有关原始代码的一些事项。

首先,让我们看一下这个声明:

words_copy = words

没有按照你的想法去做,也没有必要。这不会创建 words 的副本,它只是创建一个新变量 words_copy 并将其指向现有的 words 值。因此,如果您更改 words,您也会更改 words_copy

您想要的是 words_copy = copy.deepcopy(words) 但在这种情况下这是不必要的,因为您在迭代时不会更改 words 的状态。

接下来,这一行:

if dict[(words[word], words[word + 1])] in dict:
dict.update(words[word+2])

有一些缺陷。首先,如果元组尚未在字典中,那么这将引发一个关键错误。这肯定会在第一次迭代时发生。其次,字典的更新方法将传递的字典添加到您正在调用的字典中。您想要做的是更新该键处的字典值。

所以你想要:

if (words[word], words[word + 1]) in dict:
# Add to the existing list
dict(words[word], words[word + 1]).append(words[word+2])
else:
# Create a new list
dict(words[word], words[word + 1]) = [words[word+2]]

最后,这个 block 是不必要的:

if word == len(words_copy) - 3:
break

相反,只需迭代到倒数第三个索引,如下所示:

for word in range(0, len(words) - 2):

总而言之,您可以使用这些更改来修复原始版本:

def make_chains(corpus):
"""Takes an input text as a string and returns a dictionary of
markov chains."""
dict = {}
for line in corpus:
line = line.replace(',', "")
words = line.split()
for word in range(0, len(words) - 2):
if (words[word], words[word + 1]) in dict:
# Add to the existing list
dict[(words[word], words[word + 1])].append(words[word + 2])
else:
# Create a new list
dict[(words[word], words[word + 1])] = [words[word + 2]]

return dict

希望这有帮助!

关于python - 添加到字典中键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32103802/

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