【问题标题】:Creating a dict out of a larger corpus [duplicate]从更大的语料库中创建一个字典 [重复]
【发布时间】:2020-11-15 18:13:24
【问题描述】:

我有一个包含 30000 条消息的语料库。

corpus = [
    "hello world", 
    "i like mars", 
    "a planet called venus", 
    ... , 
    "it's all pcj500"]

我已经将它们标记化并形成了一个包含所有唯一词的word_set

word_lists = [text.split(" ") for text in corpus]
>>> [['hello', 'world'],
    ['i', 'like', 'mars'],
    ['a', 'planet', 'called', 'venus'],
    ...,
    ["it's", 'all', 'pcj500']]

word_set = set().union(*word_lists)
>>> ['hello', 'world', 'i', 'like', ..., 'pcj500']
  1. 我正在尝试创建一个字典列表,其中 word in the word_set 作为 keys,初始 values 作为 0 进行计数。
  2. 如果word in word_set 出现在word_list in word_lists 中,则 适当的计数作为

对于第 1 步,我是这样做的,

tmp = corpus[:10]
word_dicts = []
for i in range(len(tmp)):
    word_dicts.append(dict.fromkeys(list(word_set)[:30], 0))

word_dicts
>>> [{'hello': 0,
  'world': 0,
  'mars': 0,
  'venus': 0,
  'explore': 0,
  'space': 0}]

问题:

如何针对word_set中的所有项目对语料库中的所有文本执行dict.fromkeys操作?对于整个语料库,我的内存不足。应该有更好的方法来做到这一点,但我自己找不到。

【问题讨论】:

    标签: python dictionary optimization corpus


    【解决方案1】:

    您可以使用 collections 中的 defaultdictCounter,它们使用惰性键。示例:

    from collections import Counter
    
    word_dicts = []
    for words_list in word_lists:
        word_dicts.append(Counter(words_list))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 2021-06-25
      • 1970-01-01
      • 2019-07-17
      • 2020-01-18
      • 2014-08-22
      • 1970-01-01
      相关资源
      最近更新 更多