【发布时间】:2019-01-01 22:33:59
【问题描述】:
我有一本字典,里面有单词和每个单词的频率。
{'cxampphtdocsemployeesphp': 1,
'emptiness': 1,
'encodingundefinedconversionerror': 1,
'msbuildexe': 2,
'e5': 1,
'lnk4049': 1,
'specifierqualifierlist': 2, .... }
现在我想使用这个字典创建一个词袋模型(我不想使用标准库和函数。我想使用算法来应用它。)
- 在字典中找到 N 个最流行的单词并计算它们。现在我们有了一本最流行单词的字典。
- 为字典中的每个标题创建一个维数等于 N 的零向量。
- 对于语料库中的每个文本,遍历字典中的单词并将相应的坐标加 1。
我有我的文本,我将使用它来使用函数创建向量。
函数看起来像这样,
def my_bag_of_words(text, words_to_index, dict_size):
"""
text: a string
dict_size: size of the dictionary
return a vector which is a bag-of-words representation of 'text'
"""
Let say we have N = 4 and the list of the most popular words is
['hi', 'you', 'me', 'are']
Then we need to numerate them, for example, like this:
{'hi': 0, 'you': 1, 'me': 2, 'are': 3}
And we have the text, which we want to transform to the vector:
'hi how are you'
For this text we create a corresponding zero vector
[0, 0, 0, 0]
And iterate over all words, and if the word is in the dictionary, we increase the value of the corresponding position in the vector:
'hi': [1, 0, 0, 0]
'how': [1, 0, 0, 0] # word 'how' is not in our dictionary
'are': [1, 0, 0, 1]
'you': [1, 1, 0, 1]
The resulting vector will be
[1, 1, 0, 1]
应用此功能的任何帮助都会非常有帮助。我正在使用 python 来实现。
谢谢,
尼尔
【问题讨论】:
-
请提供示例输出以供您输入。 (my_bag_of_words 究竟会返回什么)
标签: python python-3.x nlp text-processing information-retrieval