繁体   English   中英

将字母序列与python中的单词列表进行比较

[英]Comparing a sequence of letters to a list of words in python

我有一个按特定顺序排列的字母列表(想想老式的短信,所以我这里的按钮序列是 4266532)

letters = [['g', 'h', 'i'], ['a', 'b', 'c'], ['m', 'n', 'o'], ['m', 'n', 'o'], ['j', 'k', 'l'], ['d', 'e', 'f']]

和单词列表

words = ['i', 'am', 'an', 'old', 'man']

我想看看与这个单词列表相比,这个字母序列有多少匹配的句子。

例如,字母序列可以等于“i am old”或“i an old”

编辑:为了澄清我所说的顺序

在仍然有按钮而不是触摸屏的旧手机上。 每个按钮(或数字)都附有字母。 例如,数字/按钮“2”附有字母['a','b','c'] 数字/按钮“3”附有字母['d,'e','f'] 所以我上面的letters列表显示了当你按下4266532时屏幕上会出现哪些字母

不确定您的完整标准是什么,但由于您的列表很小,您可以执行以下操作:

from collections import Counter
from itertools import combinations, chain
letters = [['g', 'h', 'i'], ['a', 'b', 'c'], ['m', 'n', 'o'],['m', 'n', 'o'], ['j', 'k', 'l'], ['d', 'e', 'f']]
allowed = set(chain.from_iterable(letters))
words = ['i', 'am', 'an', 'old', 'man']

for phrase in combinations(words, 3):
    phrase_c = Counter(chain.from_iterable(phrase))
    if any((v > 1 and k not in "mno") or k not in allowed for k, v in phrase_c.items()):
        continue
    print(phrase)

这会给你:

('i', 'am', 'old')
('i', 'an', 'old')
('i', 'old', 'man')

如果单词始终是字母的子集,您可以删除if k not in "mno"

如果您必须按顺序排列那么它更简单,只需确保短语中的每个字母都以正确的顺序出现在子集中:

from collections import Counter
from itertools import combinations, chain

letters = [['g', 'h', 'i'], ['a', 'b', 'c'], ['m', 'n', 'o'], ['m', 'n', 'o'], ['j', 'k', 'l'], ['d', 'e', 'f']]

words = ['i', 'am', 'an', 'old', 'man']

for phrase in combinations(words, 3):
    for ind, letter in enumerate(chain.from_iterable(phrase)):
         if ind >= len(letters) or letter not in letters[ind]:
            break
    else:
        print(phrase)

这会给你:

('i', 'am', 'old')
('i', 'an', 'old')

如果您根据字母顺序对单词进行排序并过滤不包含任何字母的单词,则可以大大降低复杂性。 您还可以考虑这样一个事实,即您最多只能创建 6 个字母的短语,即4266532

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM