简体   繁体   中英

Python: How to pass key to a dictionary from the variable of a function?

Basically I have two dictionaries: one is a Counter() the other is dict()

The first one contains all the unique words in a text, as keys and each words' frequency in the text, as the values

The second contains the same unique words as keys, but the values are the definitions which are user-inputted.

The latter is what I'm having trouble implementing. I created a function which takes in a word, checks if that word is in the frequency dictionary, and if it is, allows the user to input a definition of that word (else, it will print an error). The word and its definition are then added to the second dictionary as a key-value pair (using dict.update(word=definition) ).

But whenever I run the program I get the error:

Nameerror: name '' is not defined

Here is the code:

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())

I get the feeling that either the error is very small or very big. Any help would be greatly appreciated.

EDIT: So the program now allows me to enter a definition, but returns this error once I do so:

>>> 
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
>>> 

dict.update(word=definition) won't do what you think it does. See this example:

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

As you can see, this method will always update the key word although you want the word variable to be resolved first. This won't work though because you are passing a named argument to the update function, and those named arguments are taken literally.

If you want to update the key that equals to the value of word , you can just do it like this:

someDict[word] = definition

dfn_dict.update(word = definition) is equivalent to dfn_dict.update({"word": definition}) . You want to use dfn_dict.update({word: definition}) .

input() actually evaluates the input as Python code. Use raw_input instead.

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM