好吧,我按照以下方法 https:/medium.com@phylypotext-classification-with-scikit-learn-on-khmer-documents-1a395317d195。 ,工作中的数据框架是这样布局的,并命名为 result
:
target type post
1 intj "hello world shdjd"
2 entp "hello world fddf"
16 estj "hello world dsd"
4 esfp "hello world sfs"
1 intj "hello world ddfd"
每篇文章都是独一无二的,target只是将1-16号分配给16种类型或类别中的每一种。我想用sklearn来找到16种类型中每一种类型的顶级词。
我知道你可以使用TfidfTransformer来获取一个语料库中的顶级词汇,并看了一下 Sklearn如何从每道题目中获取10个单词。 然而我不知道这到底是如何发挥数据框架的作用。
def get_top_n_words(corpus, n=None):
vec = CountVectorizer().fit(corpus)
bag_of_words = vec.transform(corpus)
sum_words = bag_of_words.sum(axis=0)
words_freq = [(word, sum_words[0, idx]) for word, idx in vec.vocabulary_.items()]
words_freq = sorted(words_freq, key=lambda x: x[1], reverse=True)
return words_freq[:n]
print(get_top_n_words(result.post, 10))
这让我在所有帖子中排名前十,但是并没有删除 “这个 “或 “和 “这样的休止符,而且。没有按类型分类。 我怎么能这样做呢?
解决方案:
分类部分 :
你可以创建一个字典,将每个主题映射到他的数据,然后在字典中得到每个主题的前n个词,例如。
# just for exmaple
corpus_dict = {"topic1": "data1", "topic2": "data2"}
# top n words dict
top_n_words_dict = {}
# iterate overall topics inside the corpus
# inorder to get top n words for each topic
for topic in corpus_dict.keys():
# map the topic to the top n words in the topic
top_n_words_dict[topic] = get_top_n_words(corpus_dict[topic], 10)
# print for test purposes
print(f"Topic: {topic}, top 10 words: {top_n_words_dict[topic]}")
不要关注代码,要关注思想。
停词部分:你可以用 “停词 “的方法来解决这个问题,也可以用 “停词 “的方法来解决这个问题。
你可以使用 nltk
lib来获取所有英文停顿词。
import nltk
# get set of english stop words
stop_words = set(nltk.corpus.stopwords.words("english"))
然后你可以在计算词频之前过滤你的单词。
本文来自投稿,不代表实战宝典立场,如若转载,请注明出处:https://www.shizhanbaodian.com/40480.html