【问题标题】:Python: Nested dictionary - create if key doesn't exist, else sum 1Python:嵌套字典 - 如果键不存在则创建,否则总和 1
【发布时间】:2020-02-25 20:28:05
【问题描述】:

情景模拟
我正在尝试计算一个单词在句子中出现的次数,以获得句子列表。 每个句子都是一个单词列表。
我希望最终字典对整个语料库中的每个单词都有一个键,第二个键指示它们出现的句子,值是它出现在其中的次数。

当前解决方案
以下代码正常工作:

dfm = dict()
for i,sentence in enumerate(setences):
    for word in sentence:
        if word not in df.keys():
            dfm[word] = dict()
        if i not in dfm[word].keys():
            dfm[word][i] = 1
        else:
            dfm[word][i] += 1

问题
有没有更简洁的方法可以用 python 做到这一点?
我已经浏览过this 和this 他们建议使用的地方:

dic.setdefault(key,[]).append(value)  

和,

d = defaultdict(lambda: defaultdict(dict))

我认为它们是很好的解决方案,但我不知道如何使其适应我的特定解决方案。

谢谢!

【问题讨论】:

  • 使用Counter ?
  • @temmo Collections Counter 通常是一个不错的选择,但看看 OP 想要的结构,我认为 defaultdict 更有意义。
  • 额外评论:在准备好您的问题并在 SO 上发布之前寻找可能的解决方案方面做得很好。你值得一颗星!

标签: python dictionary nested


【解决方案1】:

假设你有这个输入:

sentences = [['dog','is','big'],['cat', 'is', 'big'], ['cat', 'is', 'dark']]

您的解决方案:

dfm = dict()
for i,sentence in enumerate(sentences):
    for word in sentence:
        if word not in dfm.keys():
            dfm[word] = dict()
        if i not in dfm[word].keys():
            dfm[word][i] = 1
        else:
            dfm[word][i] += 1

默认字典:

from collections import defaultdict

dfm2 = defaultdict(lambda: defaultdict(int))

for i,sentence in enumerate(sentences):
    for word in sentence:
        dfm2[word][i] += 1 

测试:

dfm2 == dfm  # True


#{'dog': {0: 1},
# 'is': {0: 1, 1: 1, 2: 1},
# 'big': {0: 1, 1: 1},
# 'cat': {1: 1, 2: 1},
# 'dark': {2: 1}}

【讨论】:

  • 这正是我想到的答案,所以我冒昧地更改它以将其与原始解决方案进行比较。希望你没问题@rassar。
  • @AntonvBR 太好了!谢谢!
【解决方案2】:

对于更简洁的版本,请使用Counter

from collections import Counter

string = 'this is america this is america'
x=Counter(string.split())
print(x)

输出

Counter({'this': 2, 'is': 2, 'america': 2})

如果想要一些自己的代码,那么

从@rassar 复制输入数据(句子)

def func(list_:list):      
    dic = {}
    for sub_list in list_:
        for word in sub_list:
            if word not in dic.keys():
                dic.update({word:1})
            else:
                dic[word]+=1
    return dic


sentences = [['dog','is','big'],['cat', 'is', 'big'], ['cat', 'is', 'dark']]


print(func(sentences))

输出

{'dog': 1, 'is': 3, 'big': 2, 'cat': 2, 'dark': 1}

【讨论】:

  • 这是不正确的 - OP 想要一个字典将每个单词映射到一个字典,其中第二个字典映射 {sentence number: count of words in that sentence}。
  • @rassar 还添加了字典映射
  • 我会在函数的开头添加一个split(),这样我们就可以直接输入像sentences = ["dog is big", "cat is dark"]这样的花哨的东西。
  • @Guimute 我已经添加了这种方式,您可以在以前的编辑中看到这种方式,但是 Op 没有提供任何输入数据,所以我使用 rassar 输入数据并修改代码:)
【解决方案3】:

使用计数器

from collections import Counter
    
sentences = ["This is Day", "Never say die", "Chat is a good bot", "Hello World", "Two plus two equals four","A quick brown fox jumps over the lazy dog", "Young chef, bring whisky with fifteen hydrogen ice cubes"]

sentenceWords = ( Counter(x.lower() for x in sentence.split()) for sentence in sentences)

#print result
print("\n".join(str(c) for c in sentenceWords))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    相关资源
    最近更新 更多