python字典键值对可以通过参数传递吗_Python:如何从函数的变量向字典传递键?...

基本上我有两本字典:一本是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

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 "", line 1

To await

^

SyntaxError: unexpected EOF while parsing

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值