所以我采取了自然语言处理阶级和我需要创建一个三元语言模型来生成,看起来"现实"的基础了一些样本数据在一定程度上随机文本.
根本需要创建一个"三元组"来保存各种3个字母的语法单词组合.我的教授暗示这可以通过使用我试图使用的字典词典来完成:
trigram = defaultdict( defaultdict(defaultdict(int)))
Run Code Online (Sandbox Code Playgroud)
但是我收到的错误是:
trigram = defaultdict( dict(dict(int)))
TypeError: 'type' object is not iterable
Run Code Online (Sandbox Code Playgroud)
如何创建3层嵌套字典或int值字典词典字典?
如果他们不知道如何回答,我猜人们就堆栈溢出问题投票.我将添加一些背景知识,以便为那些愿意提供帮助的人更好地解释这个问题.
该三元组用于跟踪三字模式.它们被用在文本语言处理软件中,几乎无处不在自然语言处理"思考siri或google现在".
如果我们将3个级别的字典指定为dict1 dict2和dict3,那么解析文本文件并阅读语句"The boy runs"将具有以下内容:
dict1有一个"the"键.访问该密钥将返回包含密钥"boy"的dict2.访问该密钥将返回最终的dict3,其中包含现在访问该密钥的密钥"runs"将返回值1.
这象征着在这篇文章中"男孩跑"已经出现过一次.如果我们再次遇到它,那么我们将遵循相同的过程并将1增加到2.如果我们遇到"女孩走路",那么dict2"the"键字典现在将包含另一个"女孩"的键,它将具有一个具有"行走"键和值1等的dict3.最终在解析了大量文本(并跟踪单词计数)之后,你将有一个三元组,它可以根据它们在先前解析的文本中出现的次数来确定导致3个单词组合的某个起始单词的可能性. .
这可以帮助您创建语法规则来识别语言,或者在我的情况下创建随机生成的文本,看起来非常像语法英语.我需要一个三层字典,因为在3个单词组合的任何位置,可以有另一个单词可以创建一组完整的不同组合.我尽我最大的努力,尽我所能来解释卦及其背后的目的......我刚刚在几周前就说过这个课程.
现在......所有这一切都在说.我如何创建一个字典词典字典,其基本字典在python中包含int类型的值?
trigram = defaultdict(defaultdict(defaultdict(int)))
为我抛出一个错误
pco*_*ing 12
我之前尝试过嵌套defaultdict,解决方案似乎是一个lambda调用:
trigram = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
trigram['a']['b']['c'] += 1
Run Code Online (Sandbox Code Playgroud)
它不漂亮,但我怀疑嵌套字典建议是为了有效查找.
通常,要创建三元组的嵌套字典,已发布的解决方案可能会起作用.如果您想扩展一个更通用的解决方案的想法,您可以执行以下操作之一,其中一个采用Perl的AutoVivification,另一个采用collection.defaultdict.
解决方案1:
class ngram(dict):
"""Based on perl's autovivification feature."""
def __getitem__(self, item):
try:
return super(ngram, self).__getitem__(item)
except KeyError:
value = self[item] = type(self)()
return value
Run Code Online (Sandbox Code Playgroud)
解决方案2:
from collections import defaultdict
class ngram(defaultdict):
def __init__(self):
super(ngram, self).__init__(ngram)
Run Code Online (Sandbox Code Playgroud)
使用解决方案1进行演示
>>> trigram = ngram()
>>> trigram['two']['three']['four'] = 4
>>> trigram
{'two': {'three': {'four': 4}}}
>>> a['two']
{'three': {'four': 4}}
>>> a['two']['three']
{'four': 4}
>>> a['two']['three']['four']
4
Run Code Online (Sandbox Code Playgroud)
使用解决方案2进行演示
>>> a = ngram()
>>> a['two']['three']['four'] = 4
>>> a
defaultdict(<class '__main__.ngram'>, {'two': defaultdict(<class '__main__.ngram'>, {'three': defaultdict(<class '__main__.ngram'>, {'four': 4})})})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7786 次 |
| 最近记录: |