Python:如何将键传递给一个函数变量的字典? [英] Python: How to pass key to a dictionary from the variable of a function?
问题描述
Counter()
另一个是 dict()
第一个包含文本中的所有唯一字,作为键和每个单词在文本中的频率,作为值
第二个包含与键相同的唯一字,但值是用户输入的定义。
后者是我在执行时遇到的问题。我创建了一个函数,它接收一个单词,检查该单词是否在频率字典中,如果是,则允许用户输入该单词的定义(否则,将输出错误)。然后将单词及其定义作为键值对(使用 dict.update(word = definition)
)添加到第二个字典中。
但是每当我运行该程序时,都会收到错误信息:
Nameerror:name''未定义
以下是代码:
导入字符串
导入集合
导入pickle
freq_dict = collections.Counter()
dfn_dict = dict()
def cleanedup(fh):
for line in fh:
字=''
字符在线:
如果字符在string.ascii_letters中:
字+字符
其他:
产生字
字=''
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):
全球span_freq_dict
l = pickle.loads(span_freq_dict)
返回l.most_common()[N]
$ b $ def show_N_freq_words(N):
global span_freq_dict
l = $ pickle.loads(span_freq_dict)
返回l.most_common(N)
def define_word(word):
如果freq_dict中的单词:
definition = eval(input ('请定义'+ str(word)+':'))
dfn_dict({word:definition})
else:
return print('Word not in dictionary!')
process_book('DQ.txt')
process_book('HV.txt')
#这是为了看看if / else正在工作
define_word('asdfs')
#这是我想添加的实际单词
define_word('de')
print(dfn_dict .items())
我觉得这个错误非常小或非常大。任何帮助,将不胜感激。编辑:所以程序现在允许我输入一个定义,但一旦我这样做返回这个错误:$ / b>
编辑:
$ b
>>>
字不在字典中!
请定义esperar:等待
Traceback(最近一次调用最后一次):
文件C:\ Users \ User 3.1 \Desktop\Code Projects\dict.py ,第50行,在< module>
define_word('esperar')
文件C:\ Users \ User 3.1 \Desktop\Codes Projects\dict.py,第37行,在define_word
definition = eval('请定义'+ str(word)+':'))
文件< string>,第1行
等待
^
语法错误:意想不到的EOF,同时解析
>>>
dict.update =定义)
不会做你认为它的作用。看到这个例子:
>>> someDict = {}
>>> word ='foo'
>>> definition ='bar'
>>> someDict.update(word = definition)
>>> someDict
{'word':'bar'}
正如您所见,将始终更新密钥字
,但您希望首先解决字
变量。这不会起作用,因为您将命名参数传递给 update
函数,并且这些命名参数是从字面上获取的。
如果您想更新等于 word
值的关键字,您可以这样做:
someDict [word] =定义
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
这篇关于Python:如何将键传递给一个函数变量的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!