在python中使用sklearn for variablengrams计算TFIDF

2024-04-27 22:28:17 发布

您现在位置:Python中文网/ 问答频道 /正文

问题: 使用scikit学习如何找到特定词汇表中变量n-gram的命中数。你知道吗

解释。 我从here得到了一些例子。你知道吗

假设我有一个语料库,我想找出有多少点击量(计数)有如下词汇:

myvocabulary = [(window=4, words=['tin', 'tan']),
                (window=3, words=['electrical', 'car'])
                (window=3, words=['elephant','banana'])

我在这里所说的窗口是单词出现的长度。具体如下:

“天坛”被击中(4字以内)

“锡狗晒”被打(4字以内)

“锡狗猫被打(4字以内)

“铁皮车日蚀晒黑”不打。锡和棕褐色之间的距离超过4个字。你知道吗

我只想计算一下文本中出现了多少次(window=4,words=['tin','tan'])以及其他所有文本中出现的次数,然后将结果添加到pandas中以计算tf-idf算法。 我只能找到这样的东西:

from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(vocabulary = myvocabulary, stop_words = 'english')
tfs = tfidf.fit_transform(corpus.values())

其中词汇表是一个简单的字符串列表,可以是单个单词,也可以是多个单词。你知道吗

除了从scikitlearn:

class sklearn.feature_extraction.text.CountVectorizer
ngram_range : tuple (min_n, max_n)

要提取的不同n-gram的n值范围的上下限。n的所有值,以便使用min\n<;=n<;=max\n。你知道吗

也没用。你知道吗

有什么想法吗? 谢谢。你知道吗


Tags: 词汇表text文本sklearnwindow单词featuretfidf
1条回答
网友
1楼 · 发布于 2024-04-27 22:28:17

我不确定是否可以使用CountVectorizerTfidfVectorizer来完成。我编写了自己的函数,如下所示:

import pandas as pd
import numpy as np
import string 

def contained_within_window(token, word1, word2, threshold):
  word1 = word1.lower()
  word2 = word2.lower()
  token = token.translate(str.maketrans('', '', string.punctuation)).lower()
  if (word1 in token) and word2 in (token):
      word_list = token.split(" ")
      word1_index = [i for i, x in enumerate(word_list) if x == word1]
      word2_index = [i for i, x in enumerate(word_list) if x == word2]
      count = 0
      for i in word1_index:
        for j in word2_index:
          if np.abs(i-j) <= threshold:
            count=count+1
      return count
  return 0

SAMPLE:

corpus = [
    'This is the first document. And this is what I want',
    'This document is the second document.',
    'And this is the third one.',
    'Is this the first document?',
    'I like coding in sklearn',
    'This is a very good question'
]

df = pd.DataFrame(corpus, columns=["Test"])

您的df将如下所示:

    Test
0   This is the first document. And this is what I...
1   This document is the second document.
2   And this is the third one.
3   Is this the first document?
4   I like coding in sklearn
5   This is a very good question

现在可以按如下方式应用contained_within_window

sum(df.Test.apply(lambda x: contained_within_window(x,word1="this", word2="document",threshold=2)))

你会得到:

2

您可以运行for循环来检查不同的实例。 你可以用这个来构造你的pandas df并在上面应用TfIdf,这很简单。你知道吗

希望这有帮助!你知道吗

相关问题 更多 >