在Python中使用Flashtext计算关键字出现的次数

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

我有一个YouTube视频数据集,其中包含它们的描述。对于每个视频,我想添加一列来显示字符串“ bit.ly”出现了多少次。我可以使关键字查找器正常工作,但是无法将结果格式化为一个列表,然后可以将其放回到数据框中进行分析。

这是我的代码:

from flashtext import KeywordProcessor
keyword=KeywordProcessor()
dictionary = {
    "http://": ['http://'],
    "bit.ly": ['bit.ly']
}

keyword.add_keywords_from_dict(dictionary)

test_column = X_train['description']
list_of_descriptions = test_column.values.T.tolist()
for i in list_of_descriptions:
    global_list = []
    words=[]
    words.append(keyword.extract_keywords(i))
    print(words)

screenshot of my code / results

所以,我希望将print(words)的输出格式化为列表。如果我在打印字词行的正下方添加诸如global_list.append(words)之类的行,它将无法正常工作。我认为这会起作用,因为如果将print('test')放入for循环中,它将打印'test'正确的次数,表明程序运行了很多次。我不知道为什么每次循环时都无法将变量'words'追加到此列表中。我想为数据集中的每一行提供一个列表,其中包含术语“ bit.ly”的出现次数。

谢谢。

python machine-learning
1个回答
0
投票

尝试此代码:

from flashtext import KeywordProcessor
keyword=KeywordProcessor()
dictionary = {
    "http://": ['http://'],
    "bit.ly": ['bit.ly']
}

keyword.add_keywords_from_dict(dictionary)

#test_column = X_train['description']
# Fake data
list_of_descriptions = ['bit.ly bit.ly', 'lol http://', 'I love pizza', 'bit.ly']#test_column.values.T.tolist()

words=[]
for i in list_of_descriptions:
    words.append(len(keyword.extract_keywords(i)))

或使用列表推导:

words = [len(keyword.extract_keywords(i)) for i in list_of_descriptions]

在两种情况下,words都包含:

# [2, 1, 0, 1]

如果您想知道每个事件的不同值,可以执行以下操作:

[{k: l.split().count(k) for k in dictionary} for l in list_of_descriptions]

[{'http://': 0, 'bit.ly': 2},
 {'http://': 1, 'bit.ly': 0},
 {'http://': 0, 'bit.ly': 0},
 {'http://': 0, 'bit.ly': 1}]

[相反,如果您想计算每个句子中所有单词的出现次数:

from collections import Counter

[Counter(i.split()) for i in list_of_descriptions]

[Counter({'bit.ly': 2}),
 Counter({'lol': 1, 'http://': 1}),
 Counter({'I': 1, 'love': 1, 'pizza': 1}),
 Counter({'bit.ly': 1})]
© www.soinside.com 2019 - 2024. All rights reserved.