文本中最常见的 n 个词
Most common n words in a text
我目前正在学习使用 NLP。我面临的问题之一是在文本中找到最常见的 n 个词。考虑以下因素:
text=['Lion Monkey Elephant Weed','Tiger Elephant Lion Water Grass','Lion Weed Markov Elephant Monkey Fine','Guard Elephant Weed Fortune Wolf']
假设 n = 2。我不是在寻找最常见的双字母组。我正在搜索文本中出现次数最多的两个词。比如,上面的输出应该是:
'Lion' & 'Elephant': 3
'Elephant' & 'Weed': 3
'Lion' & 'Monkey': 2
'Elephant' & 'Monkey': 2
等等..
谁能建议一个合适的方法来解决这个问题?
这很棘手,但我为你解决了,我使用空 space 来检测 elem 是否包含超过 3 个词:-) 因为如果 elem 有 3 个词,那么它必须是 2 个空 spaces :-) 在这种情况下,只会返回包含 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
如下。
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)
我目前正在学习使用 NLP。我面临的问题之一是在文本中找到最常见的 n 个词。考虑以下因素:
text=['Lion Monkey Elephant Weed','Tiger Elephant Lion Water Grass','Lion Weed Markov Elephant Monkey Fine','Guard Elephant Weed Fortune Wolf']
假设 n = 2。我不是在寻找最常见的双字母组。我正在搜索文本中出现次数最多的两个词。比如,上面的输出应该是:
'Lion' & 'Elephant': 3 'Elephant' & 'Weed': 3 'Lion' & 'Monkey': 2 'Elephant' & 'Monkey': 2
等等..
谁能建议一个合适的方法来解决这个问题?
这很棘手,但我为你解决了,我使用空 space 来检测 elem 是否包含超过 3 个词:-) 因为如果 elem 有 3 个词,那么它必须是 2 个空 spaces :-) 在这种情况下,只会返回包含 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
如下。
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)