'When trying to convert a phrase structure tree to chomsky normal form, I get a TypeError: list indices must be integers or slices, not tuple
I'm trying to convert a phrase structure tree into chomsky normal form, but when I attempt with a small test tree I get the type error "Type error: list indices must be integers or slices, not tuple". The error is raised at the line of the test tree with ["NN", "board"]]]], so I'm not sure exactly what part of the code things go wrong. Any input would be much appreciated. This is the full error:
Traceback (most recent call last):
File "my_cnf.py", line 78, in <module>
["NN", "board"]]]]
TypeError: list indices must be integers or slices, not tuple
And here is my code:
new_tree = []
if len(tree) > 3:
new_label = str(tree[0]) + "|" + str(tree[1][0])
new_tree.append(new_label)
new_tree.append(tree[2:])
cnf(new_tree)
cnf(new_label)
return new_tree
elif len(tree) == 3:
return [tree[0], cnf(tree[1]), cnf(tree[2])]
elif len(tree) == 2 and (type(tree[0]) == list or type(tree[1]) == list):
new_label = str(tree[0]) + "|" + str(tree[1][0])
new_tree.append(new_label)
new_tree += tree[1][1:]
return cnf(new_tree)
elif len(tree) == 2 and (type(tree[0]) != list and type(tree[1]) != list):
new_tree = tree
return new_tree
print(new_tree)
ex_tree = ["S",
["NP",
["NNP", "Pierre"],
["NNP", "Vinken"]],
["VP",
["MD", "will"],
["ADVP",
["RB", "soon"]]
["VP",
["VB", "join"],
["NP",
["DT", "the"],
["NN", "board"]]]]
[".", "."]]
Solution 1:[1]
It seems you are missing some commas, causing Python to think you stopped defining the array and now want to reference elements of it by indexing. The missing commas should be after ["RB", "soon"]] and after ["NN", "board"]]]], so you end up with:
ex_tree = ["S",
["NP",
["NNP", "Pierre"],
["NNP", "Vinken"]],
["VP",
["MD", "will"],
["ADVP",
["RB", "soon"]],
["VP",
["VB", "join"],
["NP",
["DT", "the"],
["NN", "board"]]]],
[".", "."]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Spiny Norman |
