python - 识别出现在不到 1% 的语料库文档中的单词
问题描述
我有一个客户评论语料库,想识别稀有词,对我来说,这些词出现在不到 1% 的语料库文档中。
我已经有了一个可行的解决方案,但是对于我的脚本来说太慢了:
# Review data is a nested list of reviews, each represented as a bag of words
doc_clean = [['This', 'is', 'review', '1'], ['This', 'is', 'review', '2'], ..]
# Save all words of the corpus in a set
all_words = set([w for doc in doc_clean for w in doc])
# Initialize a list for the collection of rare words
rare_words = []
# Loop through all_words to identify rare words
for word in all_words:
# Count in how many reviews the word appears
counts = sum([word in set(review) for review in doc_clean])
# Add word to rare_words if it appears in less than 1% of the reviews
if counts / len(doc_clean) <= 0.01:
rare_words.append(word)
有谁知道这个更快的实现?通过每个单独的评论对每个单独的单词进行迭代似乎非常耗时。
在此先感谢并致以最良好的祝愿,马库斯
解决方案
这可能不是最有效的解决方案,但它易于理解和维护,我自己也经常使用它。我使用计数器和熊猫:
import pandas as pd
from collections import Counter
将计数器应用于每个文档并构造一个词频矩阵:
df = pd.DataFrame(list(map(Counter, doc_clean)))
矩阵中的某些字段未定义。它们对应于特定文档中未出现的单词。计算出现次数:
counts = df.notnull().sum()
现在,选择不经常出现的单词:
rare_words = counts[counts < 0.05 * len(doc_clean)].index.tolist()
推荐阅读
- assembly - 如何在 nasm x86 的 rax 中返回或读取负符号字节值?
- excel - VBA - 将最后一行公式复制到新行(表)
- ruby - 有谁知道为什么 IRB 在块中给出语法错误?
- node.js - 如何在没有 Gulp 的情况下将 sass 流式传输到 browserSync?
- python - 为什么声音在其余代码之前播放?
- python - 降维 – PCA 解释
- python - 如何在 MEL 中从顶点到顶点绘制曲线
- http - 如何保护 Firebase 云功能
- discord.py - 如何使用 Discord.py 中内置的“命令菜单”?
- linux - 为 linux 制作一个小型可执行文件