簡體   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