Python 在用户输入的单词游戏中查找单词

2 投票
3 回答
3305 浏览
提问于 2025-04-18 04:31

我正在尝试写一个程序,让用户输入一个单词,然后在这个单词中找到所有长度为4个字母或更多的单词,这些单词要在一个文本文件中。到目前为止,我的代码可以检测用户输入的单词中没有打乱的单词。例如,如果我输入houses,输出会显示househouseshoususeuses。它还应该识别hosehosesshoeshoeshues等。

我知道使用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 #user inputted word

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

所以我的问题是,在输入基本单词(在这个例子中是EXAMS)后,我如何确定这个单词中总共有多少个单词,以及用户输入的单词是否在文本文件中?还要打印出这个单词是否被找到。

3 个回答

0

像这样的代码应该可以正常运行...

wordlist=[list of words]
solutionlist=[]
userword=[userword[i] for i in range(len(userword))]
for word in wordlist:
    inword=True
    letters=[word[j] for j in range(len(word))]
    for letter in set(letters):
        if letters.count(letter)>userword.count(letter):
            inword=False
            break
    if inword:
        solutionlist.append(word)

for line in solutionlist:
    print line
0

这个可以用:

# read from file in actual implementation
all_words = [
    "foo", "bar", "baz", "hose", "hoses", "shoe", "shoes", "hues", "house",
    "houses", "ho", "us", "use", "uses", "shoe", "same", "exam", "mesa", "mass"]

RETAIN_ORDERING = False

def matches(inp, word):
    if inp[0] == word[0]:
        return (
            True if len(word) == 1 else
            False if len(inp) == 1 else
            matches(inp[1:], word[1:]))
    else:
        return matches(inp[1:], word) if len(inp) >= 2 else False

# with sorting enabled, "houses" will also match "shoe"; otherwise not
def maybe_sort(x):
    return x if RETAIN_ORDERING else ''.join(sorted(x))

inp = raw_input("enter a word: ")

results = [word for word in all_words if matches(maybe_sort(inp), maybe_sort(word))]

print results

输出结果:

$ python matches.py 
enter a word: houses
['hose', 'hoses', 'shoe', 'shoes', 'hues', 'house', 'houses', 'ho', 'us', 'use', 'uses', 'shoe']
$ python matches.py 
enter a word: exams
['same', 'exam', 'mesa']

如果你想避免像 shoe 这样的匹配,因为它的字母顺序和输入的不一样,只需要把 RETAIN_ORDERING = True 设置为真就可以了。

0

一个简单的实现方法(使用 collections.Counter):

>>> all_words = ['foo', 'bar', 'baz', 'hose', 'hoses', 'shoe', 'shoes', 'hues', 'house', 'houses', 'ho', 'us', 'use', 'uses', 'shoe', 'same', 'exam', 'mesa', 'mass']

>>> def find_hidden(user_input):
        from collections import Counter
        user_word_counts = Counter(user_input)
        for word in all_words:
            isvalid = True
            for letter, count in Counter(word).iteritems():
                if user_word_counts[letter] == 0 or user_word_counts[letter] < count:
                    isvalid = False
                    break
            if isvalid: yield word


>>> list(find_hidden("houses"))
['hose', 'hoses', 'shoe', 'shoes', 'hues', 'house', 'houses', 'ho', 'us', 'use', 'uses', 'shoe']
>>> list(find_hidden("exams"))
['same', 'exam', 'mesa']

或者,

使用排列组合的方法:

>>> all_words = ['foo', 'bar', 'baz', 'hose', 'hoses', 'shoe', 'shoes', 'hues', 'house', 'houses', 'ho', 'us', 'use', 'uses', 'shoe', 'same', 'exam', 'mesa', 'mass']
>>> def permutations(s, n): # could use itertools.permutations
        if n == 1:
            for c in s:
                yield c
        for i in range(len(s)):
            for p in permutation(s[:i]+s[i+1:], n-1):
                yield s[i] + p


>>> def find_hidden(input_str):
        for word_len in range(2, len(input_str)+1):
            for word in permutations(input_str, word_len):
                if word in all_words:
                    yield word


>>> set(find_hidden("houses"))
set(['use', 'hose', 'shoes', 'houses', 'house', 'us', 'hues', 'hoses', 'uses', 'ho', 'shoe'])
>>> set(find_hidden("exams"))
set(['mesa', 'exam', 'same'])

撰写回答