Python 有一个项目,需要嵌套的录音,我有它几乎工作,但继续得到一个索引错误
最终目标是尝试创建一个嵌套字典,该字典如下所示:Python 有一个项目,需要嵌套的录音,我有它几乎工作,但继续得到一个索引错误,python,python-3.x,Python,Python 3.x,最终目标是尝试创建一个嵌套字典,该字典如下所示: k = 2 source = 'aaabaaacaaadaaabaaabaaac' dictonary = {} for x in range(len(source)): if source[x:x+k] in dictonary.keys() and source[x+k] == dictonary[source[x:x+k][x+k]]: dictonary[source[x:x+k][x+k]] += 1
k = 2
source = 'aaabaaacaaadaaabaaabaaac'
dictonary = {}
for x in range(len(source)):
if source[x:x+k] in dictonary.keys() and source[x+k] == dictonary[source[x:x+k][x+k]]:
dictonary[source[x:x+k][x+k]] += 1
elif source[x:x+k] in dictonary.keys():
dictonary[source[x:x+k]].update({source[x+k] : 1})
else:
dictonary[source[x:x+k]] = {source[x+k] : 1}
其中,如果一个相同的字符出现在n-gram之后,则将其添加到第二个字典值中
例如:“aaa”将在第二个字典值“aa”“a”+1中添加1
大多数循环都能正常工作,只是在增加第二个字典值时遇到问题,我认为我所做的可以工作,但在引用该值时遇到问题,检查其是否相等,如果相等,则添加1
建议的解决方案是有帮助的,但如果有人能解释我为什么会出现索引错误,我们将不胜感激。
索引器:字符串索引超出范围我想到的最简单、最简单的解决方案是简单地循环遍历所有n-gram并在途中计数
{'aa': {'a': 6, 'b': 3, 'c': 2, 'd': 1}, 'ab': {'a': 3}, 'ba': {'a': 3},
'ac': {'a': 1, '': 1}, 'ca': {'a': 1}, 'ad': {'a': 1}, 'da': {'a': 1}}
遍历三角图中的字符串,并计算有向图
x+y
和下面的字母z
:
result = {}
for i in range(len(source)-k):
ngram = source[i:i+k]
if ngram not in r:
r[ngram] = {}
after = source[i+k]
if after not in r[ngram]
r[ngram][after] = 0
r[ngram][after] += 1
print(result)
注:此解决方案仅适用于k=2
count = {}
for x,y,z in zip(source, source[1:], source[2:]):
if x + y not in count: count[x + y] = {}
if z not in count[x + y]: count[x + y][z] = 0
count[x + y][z] += 1
count
#{'aa': {'a': 6, 'b': 3, 'c': 2, 'd': 1}, 'ab': {'a': 3},
# 'ba': {'a': 3}, 'ac': {'a': 1}, 'ca': {'a': 1},
# 'ad': {'a': 1}, 'da': {'a': 1}}