【发布时间】:2015-02-22 07:25:33
【问题描述】:
我在 Python 2.7 中构建了一个字谜求解器,它接受输入,找到它的所有排列,然后检查它是否匹配 this dictionary text file 中的任何单词。它工作得很好,但它有一个问题。它不仅提供完全匹配,它还提供一个匹配,其中字谜只是文本文件中单词的一部分。
例子:
输入乱码:python
可能的词:ypnoth
可能的词:python
可能的词:催眠
之所以这样做,是因为有些词如 hypnotist 或 hypnotic 包含 hypnot。解决这个错误的字谜仍然很容易,但我希望程序尽可能简单。
# 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 函数中尝试了== 运算符,但这使程序变得更糟。
【问题讨论】:
-
==应该可以工作。如果它不适用于完全匹配,那么当您从文件中提取时可能会有一些空格字符。在与任何东西进行比较之前先试用line.strip()
标签: python python-2.7 text-files anagram