我正在尝试编写一个程序,该程序允许用户输入一个单词,然后找到该单词文本文件中该单词内隐藏的所有长度为4或更大的单词。到目前为止,我的代码可以检测用户输入的单词中没有混杂的单词。例如,如果我键入“ houses”,则输出将显示“ house,houses,ho,us,use,uses”。它还应识别“软管,软管,鞋子,鞋子,颜色等”。

我知道itertools是最简单的解决方案,但是我想使用仅使用循环,字典和列表的另一种方法。

到目前为止,这是我的代码:

def main():
    filename = open('dictionary.txt').readlines()
    word_list = []
    for line in filename:
        word_list.append(line.strip())

    print 'Lets Play Words within a Word!\n'
    word = raw_input('Enter a word: ')
    words_left = 0
    for words in word_list:
        letters = list(words)
        if words in word:
            print words
            words_left += 1
        else:
            False


我尝试创建的输出格式应如下所示:

Lets play Words within a Word!

Enter a word: exams

exams ---  6 words are remaining
> same #user types in guess
Found!  # prints 'Found!' if above word is found in the dictionary.txt file

exams ---  5 words are remaining
> exam
Found!

exams ---  4 words are remaining
> mesa
Found!

exams ---  3 words are remaining
> quit() #if they type this command in the game will end


我还想添加一个游戏摘要,该摘要基于Scrabble的字母得分来跟踪用户的得分,但是后来就行了。

最佳答案

itertools.permutations是可以真正帮助您的东西。这个方便的函数接受一个序列(例如字符串),并为您提供指定长度的所有排列。

这是我建议您使用的方式:

import itertools

def main():
    with open('dictionary.txt') as file:
        word_list = set(line.strip() for line in file) # Use a set instead of a list for faster lookups

    print 'Lets Play Words within a Word!\n'
    word = raw_input('Enter a word: ')

    subwords = set() # In case a word can be made in multiple ways
    for i in range(4, len(word)+1):
        for permutation in itertools.permutations(word, i):
            word_to_check = ''.join(permutation)
            if word_to_check in word_list:
                subwords.add(word_to_check)


这会检查单词的所有可能排列,以查看哪些是单词,并保留单词中找到的所有单词的集合(无重复)。然后,当用户猜测时,您可以检查

if user_guess in subwords and user_guess not in already_found_words:

10-04 17:59