我正在尝试编写一个程序,允许用户输入一个单词,然后在单词文本文件中找到隐藏在该单词中的所有长度为 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:
