【问题标题】:How to create a dictionary of word parts from the words that start and end with the same letter如何从以相同字母开头和结尾的单词创建单词部分词典
【发布时间】: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


【解决方案1】:

正如@Ch3steR 所说,这可以通过collections.defaultdict 轻松实现。修改你的代码:

from collections import defaultdict

def read_dict(dictionary):
    a = defaultdict(set)
    with open(dictionary, 'r') as text:
        data = text.readlines()
        for i in data:
            a[outside(i)].add(inside(i))
    return a

如果你不想使用任何外部库,你可以这样做:

def read_dict(dictionary):
    a = {}
    with open(dictionary, 'r') as text:
        data = text.readlines()
        for i in data:
            key = outside(i)
            if key in a:
                a[key].add(inside(i))
            else:
                a[key] = {inside(i)}
    return a

通过比较两个代码 sn-ps,您还可以了解 collections.defaultdict 的作用以及它如何让您编写更少的代码。

【讨论】:

  • 感谢您的信任。 ;)
  • 感谢您的回答和详细的解释。
  • @arthionne 不知何故我错过了。检查编辑。您可以将 defaultdict 与任何可以在 normal 字典中保存值的内容一起使用。
【解决方案2】:

您需要将a[outside(i)] 设为一个列表并将每个新项目附加到其中,而不是每次找到新项目时都将其覆盖。

另外,当您已经在文件中为您准备好单词的第一个和最后一个字母时,为什么还要抓取这些字母?

def read_dict(dictionary):
    a = {}

    with open(dictionary, 'r') as text:
        data = text.readlines()
        value, key = data.split(' ')

        if key not in a:
            a[key] = []

        a[key].append(value[1:-1])

    return a

【讨论】:

  • 最好使用key, value, *_ = data.split(' ') 来避免使用word[1] 3 次。
  • @Ev.Kounis 谢谢。那肯定更好看:)
猜你喜欢
  • 1970-01-01
  • 2015-05-31
  • 1970-01-01
  • 1970-01-01
  • 2011-04-06
  • 2019-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多