如何从看不见的文档列表中识别术语

How to identify terms from list in unseen documents

给定一个可以由一个、两个甚至三个单词组成的预定义术语列表,问题是计算它们在一组具有自由词汇表(即很多单词)的文档中的出现次数。

terms= [
[t1],
[t2, t3],
[t4, t5, t6],
[t7],...]

需要识别该术语的文件格式为:

docs = [
[w1, w2, t1, w3, w4, t7],        #d1
[w1, w4, t4, t5, t6, wi, ...],   #d2
[wj, t7, ..] ..]                 #d3

所需的输出应该是

[2, 1, 1, ...]

这是,第一个文档有两个感兴趣的术语,第二个文档有 1 个(由三个词组成)等等。

如果术语需要占 1 个单词的长度,那么我可以轻松地按字母顺序排列每个文档,删除重复的术语(集),然后与 1 个单词的术语相交。统计重复词就是搜索结果

但是当长度项 >=2 时,事情就变得棘手了。

我一直在使用 gensim 来形成词袋并在使用新短语时检测索引

例如

dict_terms = corpora.Dictionary(phrases)

sentence = unseen_docs[0]
idxs     = dict_terms[sentence]

然后计算 seed idx 考虑索引是否是连续的,这意味着已经看到一个术语而不是其中的 2 或 3 个。

任何建议。

在 Scikit-learn(一个非常流行的 Python 机器学习包)中有一个模块可以完全满足您的要求:

操作方法如下:

首先安装sklearn

pip install scikit-learn

现在代码:

from sklearn.feature_extraction.text import CountVectorizer

vectorizer = CountVectorizer(ngram_range=(1, 3))

#Given your corpus is an iterable of strings, or a List of strings, for simplicity:
corpus = [...]

X = vectorizer.fit_transform(corpus)

print(X)

输出是一个大小为 m x n 的矩阵。例如:

[[0 1 1 1 0 0 1 0 1]
 [0 2 0 1 0 1 1 0 1]
 [1 0 0 1 1 0 1 1 1]
 [0 1 1 1 0 0 1 0 1]]

代表单词,代表文档。因此,对于每一行,您都有生成的词袋。

但是如何检索哪些词出现在哪里呢?您可以获得每个 "column" 名称,使用:

print(vectorizer.get_feature_names())

您将获得一个单词列表(单词按字母顺序排列)。

现在,假设您想知道每个词在您的语料库中出现的次数(而不是在单个文档中出现的次数)。

您作为输出收到的矩阵是一个 "numpy"(另一个包)数组。这可以通过以下方式轻松展平(对所有行求和):

import numpy as np #np is like a convention for numpy, if you don't know this already.

sum_of_all_words = np.sum(X, axis=0)

这会给你类似的东西:

[[1 4 2 4 1 1 4 1 4]]

单词的列顺序相同。

最后,您可以通过以下操作过滤字典中的术语:

dict_terms = corpora.Dictionary(phrases)
counts = {}
words = vectorizer.get_feature_names()
for idx, word in enumerate(words):
   if word in dict_terms:
      counts[word] = sum_of_all_words[0, idx]


希望对您有所帮助!

在此处阅读有关 CountVectorizer 的更多信息:https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer

(另外,看看 TFIDFVectorizer,如果你使用词袋,在大多数情况下 tf-idf 是一个巨大的升级)

我还建议您查看此页面以使用 sklearn 进行特征提取:https://scikit-learn.org/stable/modules/feature_extraction.html