为何我的Python函数会多次输出结果?附代码及相关说明
为什么你的函数会多次输出结果?
问题出在你代码里的print(token_dictionary)语句位置——它被放在了for循环的if判断块内部,每找到一个存在于in_both中的token,就会立刻打印一次当前的token_dictionary,自然会输出多次。
举个例子:如果匹配到3个符合条件的token,它就会分别打印添加第一个token后的字典、添加前两个后的字典、添加全部三个后的字典,总共3次输出。
修正步骤:
- 把
print语句移到for循环外面,等所有token处理完后再打印最终的字典 - 顺便提个小问题:你当前生成tokens的方式有问题——
str(sentences)会把句子列表转成带括号和引号的字符串,导致分词时把这些符号也当成token。应该遍历每个句子单独分词,再合并tokens。
修正后的代码如下:
from nltk.tokenize import sent_tokenize, word_tokenize def sent_dictionary(text): token_dictionary = {} both_keys = in_both.keys() sentences = sent_tokenize(text) # 修正分词逻辑:遍历每个句子分词,避免把列表转字符串带来的无效token tokens = [] for sent in sentences: tokens.extend(word_tokenize(sent)) # 也可以用一行写法简化:tokens = [token for sent in sentences for token in word_tokenize(sent)] for token in tokens: if token in both_keys: token_dictionary[token] = in_both[token] # 把print移到循环外面,只打印最终结果 print(token_dictionary)
这样修改后,函数只会在所有token处理完成后,打印一次最终构建好的token_dictionary啦。
内容的提问来源于stack exchange,提问作者Shelina
相关产品推荐
相关产品推荐

