2024-05-16 13:03:28 发布
网友
我目前正在学习与NLP合作。我面临的问题之一是在文本中找到最常见的n个单词。考虑以下事项:
text=[“狮子-猴子-大象-杂草”,“老虎-大象-狮子-水草”,“狮子-杂草-马尔科夫-大象-猴子-罚款”,“守卫-大象-杂草-财富-狼”]
假设n=2。我不是在找最普通的大人物。我正在搜索文本中最多同时出现的两个单词。与之类似,上述的输出应给出:
“狮子”大象:3 “大象”杂草:3 “狮子”猴子:2 “大象”猴子:2
诸如此类
有人能提出一个合适的方法来解决这个问题吗
这很棘手,但我为您解决了,我使用空格来检测elem是否包含3个以上的单词:-)因为如果elem包含3个单词,那么它必须是2个空格:-)在这种情况下,只有包含2个单词的elem才会返回
l = ["hello world", "good night world", "good morning sunshine", "wassap babe"] for elem in l: if elem.count(" ") == 1: print(elem)
输出
hello world wassap babe
我建议如下使用Counter和combinations
Counter
combinations
from collections import Counter from itertools import combinations, chain text = ['Lion Monkey Elephant Weed', 'Tiger Elephant Lion Water Grass', 'Lion Weed Markov Elephant Monkey Fine', 'Guard Elephant Weed Fortune Wolf'] def count_combinations(text, n_words, n_most_common=None): count = [] for t in text: words = t.split() combos = combinations(words, n_words) count.append([" & ".join(sorted(c)) for c in combos]) return dict(Counter(sorted(list(chain(*count)))).most_common(n_most_common)) count_combinations(text, 2)
这很棘手,但我为您解决了,我使用空格来检测elem是否包含3个以上的单词:-)因为如果elem包含3个单词,那么它必须是2个空格:-)在这种情况下,只有包含2个单词的elem才会返回
输出
我建议如下使用
Counter
和combinations
相关问题 更多 >
编程相关推荐