保留通过 sklearn 的 CountVectorizer() 传递的参数的原始文档元素索引,以便访问相应的词性标签



我有一个数据框架,其中包含句子和每个单词的相应词性标记(下面是我正在处理的数据的摘录(数据取自SNLI语料库)。对于我的集合中的每个句子,我想提取该单词的单字和相应的post -tag。

例如,如果我有以下内容:

vectorizer_unigram = CountVectorizer(analyzer='word', ngram_range=(1, 1), stop_words = 'english')
doc = {'sent' : ['Two women are embracing while holding to go packages .'], 'tags' : ['NUM NOUN AUX VERB SCONJ VERB PART VERB NOUN PUNCT']}
sentence = vectorizer_unigram.fit(doc['sent'])
sentence_unigrams = sentence.get_feature_names_out()

那么我将得到以下单字符输出:

array(['embracing', 'holding', 'packages', 'women'], dtype=object)

但是我不知道如何在这之后保留词性标签。我尝试用单字符做一个查找版本,但由于它们可能与句子中的单词不同(例如,如果您执行sentence.split(' ')),您不一定得到相同的标记。有什么建议,我如何提取字母和保留相应的词性标签?

在检查了sklearnCountVectorizer类的源代码之后,特别是fit函数,我不相信这个类有任何方法可以跟踪相对于提取的单图特征的原始文档元素索引:其中单图特征不一定具有相同的令牌。除了下面提供的简单解决方案之外,您可能不得不依赖其他一些方法/库来实现您想要的结果。如果有一个特定的案例失败了,我建议你把它添加到你的问题中,因为它可能有助于人们找到解决你问题的方法。

from sklearn.feature_extraction.text import CountVectorizer
vectorizer_unigram = CountVectorizer(analyzer='word', ngram_range=(1, 1), stop_words = 'english')
doc = {'sent': ['Two women are embracing while holding to go packages .'],
'tags': ['NUM NOUN AUX VERB SCONJ VERB PART VERB NOUN PUNCT']}
sentence = vectorizer_unigram.fit(doc['sent'])
sentence_unigrams = sentence.get_feature_names_out()
sent_token_list = doc['sent'][0].split()
tags_token_list = doc['tags'][0].split()
sentence_tags = []
for unigram in sentence_unigrams:
for i in range(len(sent_token_list)):
if sent_token_list[i] == unigram:
sentence_tags.append(tags_token_list[i])
print(sentence_unigrams)
# Output: ['embracing' 'holding' 'packages' 'women']
print(sentence_tags)
# Output: ['VERB', 'VERB', 'NOUN', 'NOUN']

最新更新