如何使用单个字母字符串列表作为输入生成具有最高概率的双字节结果

问题描述 投票:0回答:1

我正在学习bigram主题的自然语言处理。在这个阶段,我在Python计算中遇到了困难,但我尝试了。

我将使用未经过标记化的语料库作为我的主要原始数据集。我可以使用nltk模块生成二元组结果。但是,我的问题是如何在Python中计算以生成包含两个以上特定单词的bigrams。更具体地说,我希望找到包含来自word_of_interest中的单词的所有在corpus_A中可用的双字​​母组。

语料库= [“他并没有如此轻易地放弃,但他总是感到孤独,他的精神强大,他总是结识新朋友,以获得成功的动力和灵感,他在年轻时坚持学术诚信,他希望圣诞老人会在他是一个长大的男人后,给他更多的朋友,他不再希望圣诞老人到达他和他的朋友总是外出吃饭,但他们先清理他们的手去除沙子然后吃“

word_of_interest = ['santa','和','hand','stand','handy','sand']

我想从word_of_interest列表中获取每个单词的二元组。接下来,我想根据它们在corpus_A中的外观来获得每个二元组的频率。在频率可用的情况下,我想根据从最高到低的概率对二元组进行排序和打印。

我已经尝试了在线搜索的代码,但它没有给我输出。代码如下:

for i in corpus:
    bigrams_i = BigramCollocationFinder.from_words(corpus, window_size=5)
    bigram_j = lambda i[x] not in i
    x += 1
print(bigram_j)

不幸的是,输出并未返回我计划实现的目标。

请指教。我想要的输出将包含来自word_of_interest的特定单词的二元组,并且它们的概率如下所示排序。

[((santa, clauss), 0.89), ((he, and), 0.67), ((stands, firm), 0.34))] 
python python-3.x nlp nltk probability
1个回答
0
投票

你可以试试这段代码:

import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
vec = TfidfVectorizer(ngram_range=(2,2),use_idf=False)

corpus = ["he is not giving up so easily but he feels lonely all the time his mental is strong and he always meet new friends to get motivation and inspiration to success he stands firm for academic integrity when he was young he hope that santa would give him more friends after he is a grown up man he stops wishing for santa clauss to arrival he and his friend always eat out but they clean their hand to remove sand first before eating"]
word_of_interest = ['santa', 'and', 'hand', 'stands', 'handy', 'sand']
matrix = vec.fit_transform(corpus).toarray()
vocabulary = vec.get_feature_names()

all_bigrams = []
all_frequencies = []
for word in word_of_interest:
    for bigram in vocabulary:
        if word in bigram:
            index = vocabulary.index(bigram)
            tuple_bigram = tuple(bigram.split(' '))
            frequency = matrix[:,index].sum()
            all_bigrams.append(tuple_bigram)
            all_frequencies.append(frequency)

df = pd.DataFrame({'bigram':all_bigrams,'frequency':all_frequencies})
df.sort_values('frequency',inplace=True)
df.head()

输出是一个pandas数据帧,显示按频率排序的bigrams。

    bigram  frequency
0     (for, santa)   0.109764
19  (stands, firm)   0.109764
18    (he, stands)   0.109764
17   (their, hand)   0.109764
16      (hand, to)   0.109764

这里的基本原理是TfidfVectorizer计算在语料库的每个文档中存在令牌的次数,然后计算特定于术语的频率,然后将该信息存储在与该令牌相关联的列中。该列的索引与使用矢量化器上的方法.get_feature_names()检索的词汇表中的关联词的索引相同。然后,您只需从矩阵中选择包含标记相对频率的所有行,并沿着感兴趣的列求和。

虽然双嵌套for循环并不理想,但可能会有更高效的实现。问题是get_feature_names不返回元组,而是返回['first_token second_token',]形式的字符串列表。我有兴趣看到上面代码的后半部分更好的实现。

© www.soinside.com 2019 - 2024. All rights reserved.