2014-01-23 6 views
0

제가 작성한 사전에서 일부 값에 액세스하는 데 문제가 있습니다. 필자는 파일을 읽는 동안 두 개의 다른 사전을 만들었다. 내가 가진 코드는 이것이다 :파이썬 사전 키가 작동하지 않습니다.

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가 빈 목록으로 설정됩니다.

내가 뭘하는지/액세스가 확실하지 않습니다. 어떤 아이디어? 감사!

+0

의 결과로 출력을 표시하는 것이 더 쉬울 것 self.original_grammar.terminal_rules.items()를 사용하면 terminal_rules와 non_terminal_rules에 모두 표시 할 수 있습니다. 키/값을 개별적으로 살펴 보는 대신 사전을 보는 것이 더 쉬울 것입니다. – DivineWolfwood

+0

출력에 빈 목록이 없습니다.'[ " ','"]'는 빈 목록으로 간주되지 않습니다. 값 쌍'{ "Aux": [ "have"]}','i == "Aux"','nonterminal_rules [i] == [ "have"]'및'terminal_rules [j [ –

+0

] 0]]'KeyError'는'defaultdict (list)'에 빈리스트를 만들고'x'에 할당하는 것을 의미합니다. –

답변

1

나는 시작하고 끝내는 모든 것을 원하는 코드를 읽고 있다고 가정합니다. 그럴 경우

if RHS[0] == "'" and RHS[-1] == "'" : 
    terminal_rules[LHS].append(RHS.strip()) 

0은 문자열의 첫 번째 문자이기 때문에 :). '가 분할 문자열의 두 번째 문자가 아닌 경우 지금은 non_terminal_rules에 모든 것을 추가합니다. 당신이 모든 키로 terminal_rules을 설정하려는 경우

+0

그래, 그게 내가 생각한거야,하지만 내가 RHS [1] 대신에 RHS [0]을 사용할 때, 사전은 비어있게 끝나고, 이유는 모르겠다. ... – user3229872

0

: 길이 1이다 nonterminal_rules에서 값 쌍, 이렇게 :

nonterminal_rules = defaultdict(list) 
terminal_rules = defaultdict(list) 

for line in open(file, 'r').readlines(): 
# Do stuff here as you've done above 

terminal_rules = {key:value for key,value in nonterminal_rules.items() if len(value) == 1} 
+0

별로. nonterminal_rules [i]는 목록의 목록을 만들어야합니다. 이 생성 된 목록이 하나의 멤버 일 경우, 해당 목록의 첫 번째 인덱스를 찾아서 terminal_rules의 키로 사용하고 관련 값을 저장하려고합니다. 내 변수 창을 살펴보고 terminal_rules에 주어진 키가있는 것을 볼 수 있지만, 그 키가 있다는 것을 알 수있을지라도 코드는 두 번째 키를 만들고 빈 목록을 반환하는 것처럼 보입니다. – user3229872

+0

다음은 그 예입니다. nonterminal_rules에 항목 {AUX : [ 'Aux']}가 있고 terminal_rules에 {Aux : [ "is", "was"]} 항목이 있다고합시다. 내가 궁극적으로 원하는 것은 {AUX : [ "is", "was"]}와 같은 새 사전을 만드는 것입니다. 이를 통해 여러 항목에 대해이 작업을 수행해야하며 nonterminal_rules 쌍의 값이 len == 1 인 경우에만 (즉 {S : [NP, VP]}와 같은 항목에는 해당하지 않음) – user3229872