【问题标题】:Python: How to pass key to a dictionary from the variable of a function?Python:如何将键从函数的变量传递给字典?
【发布时间】:2015-02-10 14:24:47
【问题描述】:

基本上我有两个字典:一个是Counter(),另一个是dict()

第一个包含文本中所有唯一的单词,作为键和文本中每个单词的频率,作为值

第二个包含与键相同的唯一词,但值是用户输入的定义。

后者是我在实施时遇到的问题。我创建了一个函数,它接收一个单词,检查该单词是否在频率词典中,如果是,则允许用户输入该单词的定义(否则,它将打印错误)。然后将单词及其定义作为键值对添加到第二个字典中(使用dict.update(word=definition))。

但是每当我运行程序时,我都会收到错误:

名称错误:名称''未定义

代码如下:

import string
import collections
import pickle

freq_dict = collections.Counter()
dfn_dict = dict()

def cleanedup(fh):
    for line in fh:
        word = ''
        for character in line:
            if character in string.ascii_letters:
                word += character
            else:
                yield word
                word = ''

def process_book(textname):
    with open (textname) as doc:
        freq_dict.update(cleanedup(doc))
    global span_freq_dict
    span_freq_dict = pickle.dumps(freq_dict)


def show_Nth_word(N):
    global span_freq_dict
    l = pickle.loads(span_freq_dict)
    return l.most_common()[N]

def show_N_freq_words(N):    
    global span_freq_dict
    l = pickle.loads(span_freq_dict)
    return l.most_common(N)

def define_word(word):
    if word in freq_dict:
        definition = eval(input('Please define ' + str(word) + ':'))
        dfn_dict({word: definition})
    else:
        return print('Word not in dictionary!')



process_book('DQ.txt')
process_book('HV.txt')

# This was to see if the if/else was working
define_word('asdfs')
#This is the actual word I want to add
define_word('de')

print(dfn_dict.items())

我感觉错误要么非常小,要么非常大。任何帮助将不胜感激。

编辑:所以程序现在允许我输入定义,但一旦我这样做就会返回此错误:

>>> 
Word not in dictionary!
Please define esperar:To await
Traceback (most recent call last):
  File "C:\Users\User 3.1\Desktop\Code Projects\dict.py", line 50, in <module>
    define_word('esperar')
  File "C:\Users\User 3.1\Desktop\Code Projects\dict.py", line 37, in define_word
    definition = eval(input('Please define ' + str(word) + ':'))
  File "<string>", line 1
    To await
           ^
SyntaxError: unexpected EOF while parsing
>>> 

【问题讨论】:

    标签: python function dictionary


    【解决方案1】:

    dict.update(word=definition) 不会按照你的想法去做。看这个例子:

    >>> someDict = {}
    >>> word = 'foo'
    >>> definition = 'bar'
    >>> someDict.update(word=definition)
    >>> someDict
    {'word': 'bar'}
    

    如您所见,此方法将始终更新键 word,尽管您希望首先解析 word 变量。这不起作用,因为您将一个命名参数传递给 update 函数,而这些命名参数是按字面意思获取的。

    如果你想更新等于word的值的键,你可以这样做:

    someDict[word] = definition
    

    【讨论】:

    • 谢谢,但不幸的是,在更新代码以使用此方法时,我得到一个语法错误(在“=”符号上)。或者(如果我删除“return”并将其保留为 dfn_dict[word]=definition)再次出现 Nameerror(与以前相同)
    • 是的,你不能这样做return dfn_dict[word] = definition。您必须将其分成两行,例如dfn_dict[word] = definition,然后是 return dfn_dict。但是由于您无论如何都在修改全局 dfn_dict(顺便说一句。这里不需要调用 global),您实际上不需要返回它。
    • @ShihabDider eval(input('Please define ' + str(word) + ':')) 你肯定想把eval 放在那里。
    • 完成此操作后,我现在得到dfn_dict({word: definition}) TypeError: 'dict' object is not callable
    • 非常感谢!你完全正确,我改变了关键更新部分,回到你的建议,它现在完美运行。我刚刚意识到我忘记了.update 属性。
    【解决方案2】:

    dfn_dict.update(word = definition) 等价于dfn_dict.update({"word": definition})。你想使用dfn_dict.update({word: definition})

    【讨论】:

      【解决方案3】:

      input() 实际上将输入评估为 Python 代码。请改用raw_input

      def define_word(word):                    
          if word in freq_dict:
              definition = raw_input('Please define ' + str(word) + ':')
              global dfn_dict
              return dfn_dict.update({word: definition})
          else:
              print('Word not in dictionary!')
      
      process_book('DQ.txt')
      
      # This was to see if the if/else was working
      define_word('asdfs')
      #This is the actual word I want to add
      define_word('esperar')
      
      print(dfn_dict.items())
      

      【讨论】:

      • 不,仍然得到相同的 NameError
      • @ShihabDider 我执行了这段代码,它可以工作,你确定你将输入替换为 raw_input 吗?或者也到 eval(input(..))?
      • 我之前弄错了,它不是同一个NameError,它现在说:名称'raw_input'未定义。我还用更新的代码编辑了 OP
      • 编辑:我尝试使用 eval(input()) NameError 消失了,但现在取而代之的是:SyntaxError unxpected EOF while parsing(有关详细信息,请参阅 OP)
      • @ShihabDider 您使用的是哪个版本的 Python?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      相关资源
      最近更新 更多