从更大的语料库中创建字典
Creating a dict out of a larger corpus
我有 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']
- 我正在尝试创建一个字典列表,其中
word in the word_set
作为 keys,初始 values 作为 0
计数。
- 如果
word in word_set
出现在 word_list in word_lists
中,则
适当算作值.
第一步,我是这样做的,
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
操作?对于整个语料库,我 运行 内存不足。应该有更好的方法来做到这一点,但我无法自己找到它。
您可以使用 collections
中的 defaultdict
或 Counter
,它们使用惰性键。示例:
from collections import Counter
word_dicts = []
for words_list in word_lists:
word_dicts.append(Counter(words_list))
我有 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']
- 我正在尝试创建一个字典列表,其中
word in the word_set
作为 keys,初始 values 作为0
计数。 - 如果
word in word_set
出现在word_list in word_lists
中,则 适当算作值.
第一步,我是这样做的,
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
操作?对于整个语料库,我 运行 内存不足。应该有更好的方法来做到这一点,但我无法自己找到它。
您可以使用 collections
中的 defaultdict
或 Counter
,它们使用惰性键。示例:
from collections import Counter
word_dicts = []
for words_list in word_lists:
word_dicts.append(Counter(words_list))