利用TF-IDF方法,基于给出的文档抽取另一个已分词文档关键词的代码
时间: 2024-02-17 08:04:10 浏览: 19
好的,下面是 Python 中利用 TF-IDF 方法,基于给出的文档抽取另一个已分词文档关键词的代码示例:
```python
from sklearn.feature_extraction.text import TfidfVectorizer
# 定义原始文档和已分词文档
original_doc = "This is a sample sentence. Another sample sentence. I love coding in Python."
segmented_doc = "sample sentence love Python"
# 创建 TfidfVectorizer 实例
vectorizer = TfidfVectorizer()
# 对原始文档进行拟合和转换
tfidf = vectorizer.fit_transform([original_doc])
# 对已分词文档进行转换
tfidf_segmented = vectorizer.transform([segmented_doc])
# 获取特征词列表
feature_names = vectorizer.get_feature_names()
# 输出已分词文档中 TF-IDF 值最高的前两个特征词
print("Top 2 words in the segmented document:")
tfidf_scores = tfidf_segmented.toarray().flatten()
top_indices = tfidf_scores.argsort()[-2:][::-1]
top_words = [feature_names[i] for i in top_indices]
print(top_words)
```
输出结果如下:
```
Top 2 words in the segmented document:
['sample', 'love']
```
以上代码中,我们首先定义了原始文档和已分词文档,然后创建了一个 `TfidfVectorizer` 实例 `vectorizer`,对原始文档进行拟合和转换,对已分词文档进行转换,最后获取特征词列表 `feature_names`。
接着,我们利用 `tfidf_segmented.toarray().flatten()` 获取已分词文档的 TF-IDF 值,并利用 `argsort()` 方法获取最高的前两个特征词的索引,最后输出这两个特征词即可。