我在Python 2.7中构建了一个字谜解算器,它接受输入,找到它的所有排列,然后检查它是否与此字典文本文件中的任何单词匹配。它工作得很好,但是有一个问题。它不仅提供完全匹配,还提供匹配,其中字谜只是文本文件中单词的一部分。
例子:
输入加扰字:python
可能的词:ypnoth
可能的词:python
可能的词:催眠
这样做是因为有些词,例如催眠师或催眠药,其中包含催眠符。解决这个错误仍然很容易,但是我希望程序尽可能的简单。
# import permutations module
from itertools import permutations as prm
# take input
scrambled_word = list(str(raw_input("Input scrambled word: ")))
# empty lists that will be appended to later
prm_list = []
possible_words = []
# takes each permutation of the input and puts in a list
for i in prm(scrambled_word):
prm_list.append("".join(i))
def check(x, y):
# open list of words
dictionary = file('E:\MRP\Text_Files\dictionary.txt')
# check each line in the dictionary against each item
# in the list of permutations and add it to another empty list if it's a match
for line in dictionary:
for i in x:
if i in line:
y.append(i)
check(prm_list, possible_words)
# delete duplicates
possible_words = list(set(possible_words))
# print out possible words
for i in possible_words:
print "Possible Word: " + i
比较排列和字典时,我怎么能只打印出完全匹配的内容?我已经==
在check
函数中尝试了运算符,但是这使程序变得更糟。
因为您要检查withtin
操作(if i in line
),所以您需要检查,==
但是由于行\n
尾有a ,因此您需要\n
在单词的末尾添加一个。
if i+'\n' == line
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句