3 回答

TA贡献2016条经验 获得超9个赞
列表对于查找来说效率低下。你应该使用集合的字典来索引每个单词和单词中的每个字母,这样你就可以简单地使用集合交集来查找包含所有给定字母的单词:
from functools import reduce
d = {}
with open('C:\\english-dict2.txt') as f:
for l in f:
w = l.strip()
for c in set(w):
d.setdefault(c, set()).add(w)
letters = input("Please enter your letters: ")
print(reduce(lambda a, b: a & d[b], letters[1:], d[letters[0]]))
例如,给定以下单词的字典:
apple
book
cat
dog
elephant
索引字典d将变成:
{'p': {'elephant', 'apple'}, 'a': {'cat', 'elephant', 'apple'}, 'l': {'elephant', 'apple'}, 'e': {'elephant', 'apple'}, 'k': {'book'}, 'b': {'book'}, 'o': {'book', 'dog'}, 'c': {'cat'}, 't': {'cat', 'elephant'}, 'd': {'dog'}, 'g': {'dog'}, 'h': {'elephant'}, 'n': {'elephant'}}
这是上述代码的示例输入/输出,其中发现单词apple和elephant都包含字母a和e:
Please enter your letters: ae
{'apple', 'elephant'}
如果需要,您可以从这里根据给定的最小字母数轻松过滤结果集。

TA贡献1993条经验 获得超5个赞
对于您的字典,您不需要遍历 using readline(),只需执行以下操作:
with open(path) as fh:
dict = readlines()
即使出现错误,这也将安全地关闭您的文件。如果你想对单词进行查找,我会使用 aset而不是 a list,因为查找sets是 O(1),而查找list不是,它们是 O(n)。
d_set = set(dict)
这样,如果您想创建所有字母组合,您可以像这样查找它们:
import itertools
letters = input("Input your letters, please ")
def check_for_match(combos):
for combo in combos:
if combo in d_set:
yield combo
i = len(letters)
my_list = []
while i:
combos = itertools.permutations(words, i)
results = list(check_for_match(combos))
my_list = [*my_list, *results]
i-=1
这将为您提供 的所有排列letters,检查它们是否在您的字典中,并构建my_list它们。我想这就是你要找的

TA贡献1788条经验 获得超4个赞
修改 1:您不需要遍历 中的字母letters,只需
letters_list=list(letters)
足以制作字母列表。
修改2:您可以确保mini可以使用以下方法处理任何内容:
try:
mini = int(mini)
except:
mini = 2
添加回答
举报