这里有个问题.
我有一个字符串列表:
strings = ['one two three four', 'one two four five', 'four one two', 'three four']
我试图找出两个或多个字符串中共同出现的单词的组合。
,这是我想要得到的输出.
f 214
这些组合可以是两个或多个单词的任意长度。
,这是我已经看过的--尽管我没有多少运气找到任何我能为我的需要引导的东西:
发布于 2022-07-08 23:11:26
您可以计算至少两个组合的功率集,并计算这些组合:
from itertools import chain, combinations
from collections import Counter
# https://docs.python.org/3/library/itertools.html
def powerset(iterable, MIN=2):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(MIN, len(s)+1))
c = Counter(chain.from_iterable(set(powerset(s.split()))
for s in strings))
# keep counts of 2 or more
out = {k: v for k, v in c.items() if v >= 2}
输出:
{('three', 'four'): 2,
('two', 'four'): 2,
('one', 'two', 'four'): 2,
('one', 'four'): 2,
('one', 'two'): 3}
维持秩序
使用:
c = Counter(chain.from_iterable(tuple(powerset(s.split()))
for s in strings))
https://stackoverflow.com/questions/72917714
复制相似问题