【问题标题】:How to count word dictionary in Python?如何在 Python 中计算单词字典?
【发布时间】:2021-04-17 10:29:38
【问题描述】:

我有一个关于 Python 中字典处理的问题。

我想知道如何将字典与单词列表进行比较。

[我的输入示例]

text = ['fall', 'big', 'pocket', 'layer', 'park', ...]
mylist = ['spring', 'summer', 'fall', 'winter', 'school', ...]

[制作字典代码]

lst_dic = {mylist : 0 for mylist in mylist }
lst_dic

我想知道mylist中匹配到text的字数。

[失败代码]

lst_dic = {}
for w in mylist:
    if w in text_1_1:
        lst_dic[w] += 1
    else:
        lst_dic[w] = 0

因此,我想知道字典的键和值。 像这样:

{ 'spring':0,
  'summer':3,
  'fall':1,
  'winter':0,
  ...
}

然后,我想提取超过 10 个计数值的属性。

请看一下这个问题。

【问题讨论】:

    标签: python-3.x list dictionary for-loop if-statement


    【解决方案1】:

    mylist 中第一次出现键(单词)的情况下,您的代码未正确初始化lst_dic。因此,您会得到一个KeyError

    改用collections.defaultdict 来初始化字典。这使您可以从代码中删除 else 分支,并且每次遇到 text 中的一个词的频率时只增加一次。

    import collections
    
    text = ['fall', 'big', 'pocket', 'layer', 'park']
    mylist = ['spring', 'summer', 'fall', 'winter', 'school']
    
    lst_dic = collections.defaultdict(int)
    for w in mylist:
        if w in text:
            lst_dic[w] += 1
    
    # Show the counts of all `text` words occurring in `mylist`:
    print(dict(lst_dic))
    
    # Extract those with counts > 10:
    print([e for e in lst_dic if lst_dic[e] > 10])
    
    # Or, if you want it as a dictionary:
    print({e: lst_dic[e] for e in lst_dic if lst_dic[e] > 10})
    

    【讨论】:

      【解决方案2】:

      假设defaultdictlst_dic。现在,将字典 key 与文本进行比较。如果匹配则count+1。如果值大于 10,现在提取最终字典。

      from collections import defaultdict
      text = ['fall', 'big', 'pocket', 'layer', 'park']
      mylist = ['spring', 'summer', 'fall', 'winter', 'school']
      lst_dic = defaultdict(int)
      
      for w in mylist:
          if w in text:
              lst_dic[w] += 1
      result = {key: value for key, value in lst_dic.items() if value > 10}
      print(result)
      

      【讨论】:

      • for w in lst_dic.keys(): -- 我认为应该循环通过mylist
      • @costaparas 可能是这样,但他还添加了一个使用mylist制作字典的sn-p
      • 我确实在问题中看到了这一点,我认为这是在尝试初始化 lst_dic。但问题是,如果你只循环遍历lst_dic,那么计数最多为 1 - 因为它们毕竟是字典的键。您可以通过简单的示例进行验证,例如输入mylist *= 100,您应该会看到fall 带有给定样本数据的输出。
      【解决方案3】:

      为了避免使用很多循环,我更喜欢采用这种方法:

      1- 您使用 Counter() 计算 text 中的所有单词。

      from collections import Counter
      text_count = dict(Counter(text))
      

      2- 创建一个空字典 mylist_count,遍历 mylist,将其与 text_count 键匹配并设置 mylist_count 值。

      mylist_count = dict()
      for el in mylist:
          try:
              mylist_count[el] = text_count[el]
          except:
              mylist_count[el]=0
      

      【讨论】:

        猜你喜欢
        • 2013-05-24
        • 1970-01-01
        • 2021-11-03
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-14
        • 2020-03-22
        相关资源
        最近更新 更多