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'"])])

假设我有键值对 {Aux:["have"]}。问题是,如果 i = Aux,例如,x 只是设置为一个空列表,而我实际上想要等于 ["have"]。

我不确定我在做什么/访问不正确。有任何想法吗?谢谢!

4

2 回答 2

1

我假设通过阅读您的代码,您想要所有以 ' 开头和结尾的东西,对吗?在这种情况下,您可能想要

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

因为 0 是字符串的第一个字符 :)。如果 ' 不是拆分字符串的第二个字符,那么现在它会将所有内容添加到 non_terminal_rules。

于 2014-01-23T23:20:04.177 回答
0

如果您尝试设置为长度为 1 的terminal_rules每个键:值对,请执行以下操作: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}
于 2014-01-23T23:20:16.830 回答