所以我看了类似的问题,我仍然遇到同样的问题,无法弄清楚.对于这个编程任务,我正在为Clite词典的一小部分创建一个简化版本的词法分析.我正在从输入文件中提取标记,输出我的分析结果.我正在使用字典为标识符创建一个符号表.当我在不同的行上找到相同的标识符时,我需要在符号表中附加它所在的行.例如,我在第2行和第7行找到标识符"number18".因此符号表需要从{number18:2}到{number18:2,7}
当我尝试将新行号附加到当前字典条目时出现问题.我在问题标题中发布了错误.到目前为止,这是我的代码
y = 0
s2 = ()
stable = dict()
for line in open("Sample.txt","r"):
x1 = ''
for char in line:
if char.isalpha():
x1 = x1 + char
elif char.isdigit():
x1 = x1 + char
elif char == '.':
x1 = x1 + char
elif x1 != '':
break
#print (x1)
if (x1 == "for" or x1 == "bool" or x1 == "char" or x1 == "else" or x1 == "false" or x1 == "float" or x1 == "if" or x1 == "int" or x1 == "main" or x1 == "true" or x1 == "while"):
s2=(y,"Keyword",x1)
elif x1.isidentifier():
s2=(y,"Identifier",x1)
if x1 in stable.keys():
stable[x1].append(y)
else:
stable[x1]=y
elif x1.isdigit():
s2=(y,"Int",x1)
else:
s2=(y,"Float",x1)
print (s2)
y=y+1
print (stable)
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 14
您首先将您的dict值设置为int:
stable[x1]=y
Run Code Online (Sandbox Code Playgroud)
但后来你试着把它当作一个对待它list:
stable[x1].append(y)
Run Code Online (Sandbox Code Playgroud)
从list包含您的第一个开始int:
stable[x1]=[y]
Run Code Online (Sandbox Code Playgroud)
并且.append()意志有效.
或者,您可以使用defaultdict:
stable = defaultdict(list)
Run Code Online (Sandbox Code Playgroud)
然后随意追加而无需测试密钥是否已经存在:
stable[x1].append(y) # No need to do `if x1 in stable`.
Run Code Online (Sandbox Code Playgroud)
elif x1.isidentifier():
s2=(y,"Identifier",x1)
if x1 in stable.keys():
stable[x1].append(y)
else:
stable[x1]=y
Run Code Online (Sandbox Code Playgroud)
在上面的其他部分,您是integer第一次添加。所以当你append下次使用时,你会得到那个错误。
而是将您的整数包装y在一个列表中[y],当您第一次将您的值添加到您的 dict 时
else:
stable[x1]=[y]
Run Code Online (Sandbox Code Playgroud)
好吧,您已经从@Martijn 的回答中知道,defaultdict在这里使用 a将是更好的选择,因为这样您就不需要检查containmentof 了key。
但是,仍然与您在 dict 中检查密钥的方式有关:-
if x1 in stable.keys():
Run Code Online (Sandbox Code Playgroud)
您不需要使用stable.keys(),只需使用stable,keys它只会签入。
if x1 in stable:
Run Code Online (Sandbox Code Playgroud)