제가 작성한 사전에서 일부 값에 액세스하는 데 문제가 있습니다. 필자는 파일을 읽는 동안 두 개의 다른 사전을 만들었다. 내가 가진 코드는 이것이다 :파이썬 사전 키가 작동하지 않습니다.
nonterminal_rules = defaultdict(list)
terminal_rules = defaultdict(list)
for line in open(file, 'r').readlines():
LHS,RHS = line.strip().split("->")
if RHS[1] == "'" and RHS[-1] == "'" :
terminal_rules[LHS].append(RHS.strip())
else:
nonterminal_rules[LHS].append(RHS.split())
for i in nonterminal_rules:
for j in nonterminal_rules[i]:
if len(j) == 1:
x = terminal_rules[j[0]])
여기
내 딕셔너리의 키와 값은 다음과 같습니다
print(self.original_grammar.terminal_rules.items())
dict_items([('NN ', ["'body'", "'case'", "'immunity'", "'malaria'", "'mouse'", "'pathogen'", "'research'", "'researcher'", "'response'", "'sepsis'", "'system'", "'type'", "'vaccine'"]), ('NNS ', ["'cells'", "'fragments'", "'humans'", "'infections'", "'mice'", "'Scientists'"]), ('Prep ', ["'In'", "'with'", "'in'", "'of'", "'by'"]), ('IN ', ["'that'"]), ('Adv ', ["'today'", "'online'"]), ('PRP ', ["'this'", "'them'", "'They'"]), ('Det ', ["'a'", "'A'", "'the'", "'The'"]), ('RP ', ["'down'"]), ('AuxZ ', ["'is'", "'was'"]), ('VBN ', ["'alerted'", "'compromised'", "'made'"]), ('Adj ', ["'dendritic'", "'immune'", "'infected'", "'new'", "'Systemic'", "'weak'", "'whole'", "'live'"]), ('VBN ', ["'discovered'"]), ('Aux ', ["'have'"]), ('VBD ', ["'alerted'", "'injected'", "'published'", "'rescued'", "'restored'", "'was'"]), ('COM ', ["','"]), ('PUNC ', ["'?'", "'.'"]), ('PossPro ', ["'their'", "'Their'"]), ('MD ', ["'Will'"]), ('Conj ', ["'and'"]), ('VBP ', ["'alert'", "'capture'", "'display'", "'have'", "'overstimulate'"]), ('VB ', ["'work'"]), ('VBZ ', ["'invades'", "'is'", "'shuts'"]), ('NNP ', ["'Dr'", "'Jose'", "'Villadangos'"])])
하는의 내가 키 - 값 쌍 있다고 가정 해 봅시다 {보조가 : "이"]}. 예를 들어, i = Aux 일 경우 실제로는 [ "have"]와 같을 때 x가 빈 목록으로 설정됩니다.
내가 뭘하는지/액세스가 확실하지 않습니다. 어떤 아이디어? 감사!
의 결과로 출력을 표시하는 것이 더 쉬울 것 self.original_grammar.terminal_rules.items()를 사용하면 terminal_rules와 non_terminal_rules에 모두 표시 할 수 있습니다. 키/값을 개별적으로 살펴 보는 대신 사전을 보는 것이 더 쉬울 것입니다. – DivineWolfwood
출력에 빈 목록이 없습니다.'[ " ','"]'는 빈 목록으로 간주되지 않습니다. 값 쌍'{ "Aux": [ "have"]}','i == "Aux"','nonterminal_rules [i] == [ "have"]'및'terminal_rules [j [ –
] 0]]'KeyError'는'defaultdict (list)'에 빈리스트를 만들고'x'에 할당하는 것을 의미합니다. –