在文件中查找字谜

时间:2012-10-22 01:25:46

标签: python anagram

我想要一个程序来查找文件中的字谜。例如:

>>>anagram('words.txt', 'top')
top
pot

该文件将包含一长串没有空格的单词。

tapmatlamebrainfamelookcookkoolkoocnamemane

这是我目前的代码:

def anagrams(filename, word):
    infile = open(filename, 'r')
    if not word:
        return ['']
    ret = []
    for i, d in enumerate(word):
        perms = anagrams(word[:i] + word[i+1:])
        for perm in perms:
            ret.append(d + perm)
    for i in ret:
        if i in infile:
            print (i)
        else:
            pass

1 个答案:

答案 0 :(得分:1)

这应该做我认为你想做的事情

def anagram(filepath, word):
    with open(filepath) as f:
        text = ''.join(line.strip() for line in file)
    for i in xrange(len(text)-len(word):
        prop = text[i:i+len(word)]
        if all(char in word for char in prop) and all(prop.count(char) == prop.count(word) for char in prop):
            print prop

请注意,如果您的文件只有两个单词“hi”和“there”作为“hithere”,并且您查找“ith”的字谜,则会打印"hit"