簡體   English   中英

如何使用 TFIDF 為 python 中的每一行提取關鍵字?

[英]How to extract keywords using TFIDF for each row in python?

我有一列只有文字。 我需要使用 TFIDF 從每一行中提取頂級關鍵字。

示例輸入:

df['Text']
'I live in India',
'My favourite colour is Red', 
'I Love Programming'

預期 output:

 df[Text]                            df[Keywords]
'I live in India'                  'live','India'
'My favourite colour is Red'       'favourite','colour','red'
'I Love Programming'               'love','programming'

我怎么得到這個? 我嘗試編寫以下代碼

tfidf = TfidfVectorizer(max_features=300, ngram_range = (2,2))
Y = df['Text'].apply(lambda x: tfidf.fit_transform(x))

我收到以下錯誤Iterable over raw text documents expected, string object received。

TfidfVectorizer fit_transform function 期望句子\文檔的可迭代類型(例如集合、列表等)適合 TfIdf 分數。

所以你實際上應該做的是——

Y = tfidf.fit_transform(df['Text'])

如果要標記句子,請嘗試以下代碼:

from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords

df = pd.DataFrame({'Text':['I live in India', 'My favourite colour is Red', 'I Love Programming']})
df['Keywords'] = df.Text.apply(lambda x: nltk.word_tokenize(x))
stops =  list(stopwords.words('english'))
df['Keywords'] = df['Keywords'].apply(lambda x: [item for item in x if item.lower() not in stops])
df['Keywords'] = df['Keywords'].apply(', '.join)

print(df)

                         Text                Keywords
0             I live in India             live, India
1  My favourite colour is Red  favourite, colour, Red
2          I Love Programming       Love, Programming

正如一些人已經指出的那樣,您的代碼和方法存在幾個問題,首先是您不應該將TfIdf用於此任務(TfIdf 不打算用於小型語料庫)。 您最好使用RAKEflashtext KeywordExtractor

您的代碼的另一個問題是您試圖從文本中獲取“unigrams”,但您已將矢量化器中的ngram_range設置為 (2,2),這意味着它只會找到“bigrams”(由兩個單詞組成的短語)。

如果您堅持使用您選擇的方法執行此操作,首先您需要將 df['text'] 中的句子拆分為每行一個(您可以為此使用@ManojK 解決方案的一部分),然后將每行中的文本作為一個列表:

Y = df['Text'].apply(lambda x: tfidf.fit_transform([x]))

但是,如果您想提取特征名稱(本質上是您的關鍵字),則需要在矢量化器的每次迭代之后將 function 寫入get_feature_names()lambda x: ) ZC1C425268E6AB7394D

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM