【发布时间】:2020-03-17 15:44:39
【问题描述】:
我正在尝试编写一个脚本 - read_dict(dictionary) - 它将 .txt 文件作为参数,并给出文件中每个单词的单词部分的字典。这些部分是每个单词的第一个和最后一个字母,以及其余的字母。例如,如果文件如下:
===dictionary.txt===
quack qk
quick qk
going gg
gathering gg
quirk qk
quicken qn
输出应该是:
{ 'qk' : {'uac', 'uic'}, 'gg' : {'oin', 'atherin'}, 'qn' : {'uicke' }}
这是我写的:
def outside(word):
a = word.strip()[0]
b = word.strip()[-1]
out_word = a + b
return out_word
def inside(word):
a = word.strip()[1:-1]
return a
def read_dict(dictionary):
a = {}
with open(dictionary, 'r') as text:
data = text.readlines()
for i in data:
a[outside(i)] = inside(i)
return a
但我的输出是:
{ 'qk' : 'uac', 'gg' : 'oin', 'qn' : 'uicke'}
它只保存第一个单词。我也找不到一种方法来收集所有在集合中具有相同字母的内部(单词),然后使用适当的键(例如“qk”)将它们添加到字典中。
【问题讨论】:
-
您正在寻找
collections.defaultdict。 -
你想在阅读字典时追加。
a[outside(i)].append(inside(i))。当然,您必须首先检查密钥是否存在,如果不存在,请检查a[outside(i)] =[inside(i)],以便在下次看到密钥时对其进行初始化-
标签: python python-3.x dictionary