Python 如何以单个字母字符串列表作为输入,生成概率最高的二元图的结果

Python 如何以单个字母字符串列表作为输入,生成概率最高的二元图的结果,python,python-3.x,nlp,nltk,probability,Python,Python 3.x,Nlp,Nltk,Probability,我正在为bigram主题学习自然语言处理。在这个阶段,我在Python计算方面遇到了困难,但我尝试了 我将使用这个没有进行标记化的语料库作为我的主要原始数据集。我可以使用nltk模块生成bigram结果。然而,我的问题是如何在Python中计算以生成包含两个以上特定单词的bigram。更具体地说,我希望找到语料库A中所有包含感兴趣的单词的bigrams 语料库=["他不是那么容易放弃,但他一直感到孤独他的精神很坚强,他总是结识新朋友以获得成功的动力和灵感他年轻时坚定地追求学术诚信他希望圣诞老人在

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

我将使用这个没有进行标记化的语料库作为我的主要原始数据集。我可以使用nltk模块生成bigram结果。然而,我的问题是如何在Python中计算以生成包含两个以上特定单词的bigram。更具体地说,我希望找到语料库A中所有包含感兴趣的单词的bigrams

语料库=["他不是那么容易放弃,但他一直感到孤独他的精神很坚强,他总是结识新朋友以获得成功的动力和灵感他年轻时坚定地追求学术诚信他希望圣诞老人在他长大后能给他更多的朋友他不再希望圣诞老人的到来他和他的朋友iend总是在外面吃饭,但他们在吃饭前会先把手擦干净,清除沙子“]

感兴趣的单词=[“圣诞老人”,“和”,“手”,“站”,“手”,“沙子”]

我想从感兴趣的单词列表中获取每个单词的二元图。接下来,我想根据每个二元图在语料库中的出现情况获取它们的可用频率。根据可用频率,我想根据它们的概率从高到低排序并打印出二元图

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

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)
不幸的是,输出没有返回我计划实现的目标

请告诉我。我想要的输出将有二元图,其中包含感兴趣的单词_中的特定单词及其概率,如下所示

[((santa, clauss), 0.89), ((he, and), 0.67), ((stands, firm), 0.34))] 
您可以尝试以下代码:

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()
输出是一个数据帧,显示按频率排序的bigram

    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计算语料库的每个文档中标记出现的次数,然后计算特定于术语的频率,然后将此信息存储在与该标记相关联的列中。该列的索引与使用方法。获取向量器上的\u功能\u名称()已匹配。 然后,您只需从包含令牌相对频率的矩阵中选择所有行,并沿感兴趣的列求和

不过,双嵌套for循环并不理想,可能会有更有效的实现。问题是get_feature_names返回的不是元组,而是字符串列表,格式为['first_token second_token',]。 我希望看到上述代码的后半部分有更好的实现