有没有更简单的方法在Python(2.7)中执行此操作?:注意:这不是任何花哨的东西,比如将所有局部变量放入字典中.只是我在列表中指定的那些.
apple = 1
banana = 'f'
carrot = 3
fruitdict = {}
# I want to set the key equal to variable name, and value equal to variable value
# is there a more Pythonic way to get {'apple': 1, 'banana': 'f', 'carrot': 3}?
for x in [apple, banana, carrot]:
fruitdict[x] = x # (Won't work)
Run Code Online (Sandbox Code Playgroud) 基本上我有两个词典:一个是Counter()另一个词典dict()
第一个包含文本中的所有唯一单词,作为键和每个单词在文本中的频率,作为值
第二个包含与键相同的唯一字,但值是用户输入的定义.
后者是我在实施时遇到的问题.我创建了一个函数,它接受一个单词,检查该单词是否在频率字典中,如果是,则允许用户输入该单词的定义(否则,它将打印错误).然后将单词及其定义作为键值对(使用dict.update(word=definition))添加到第二个字典中.
但每当我运行程序时,我都会收到错误消息:
Nameerror:名称''未定义
这是代码:
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 …Run Code Online (Sandbox Code Playgroud)