【问题标题】:Program that takes a set of letters from the user and prints out all of the combinations of valid words from a separate Dictionary file从用户那里获取一组字母并从单独的字典文件中打印出所有有效单词组合的程序
【发布时间】:2019-05-01 23:34:25
【问题描述】:

我当前的程序遇到了问题,该程序应该从用户输入中获取字母,对照我已有的字典文件检查它们,然后返回可以从一系列字母组成的可能单词。然后,用户输入应该指示实际返回了多少单词。我是 python 新手,在如何根据字典文件检查字母时遇到了麻烦。我非常感谢任何和所有的帮助!

这是我目前所拥有的:

def find_words (letters, dictionary):
    dictionary = open ('enable1.txt', 'r')
    r = dictionary.read()
    dictionary.close()
    dict = dictionary (word)
    w = 1
    for k in dict.keys():
        if k not in dictionary:
            w = 0
        if w == 1:
            print (word)

print (find_words (['e', 'u', 'c', 'i']))

def main ():
    letters = int (input ("please enter some letters... at least 1, but no more than 7\n>"))
    if letters < 1 and letters > 7:
        print (letters)
    try:    
       num_words = int (input ("What is the maximum number of words to display?\n>"))
  except ValueError:
       print ()

所需的输出应如下所示:

Please enter some letters... at least 1, but no more than 7
> 123
Please enter some letters... at least 1, but no more than 7
>
Please enter some letters... at least 1, but no more than 7
> abcdefghijklmnop
Please enter some letters... at least 1, but no more than 7
> tdri

What is the maximum number of words to display?
> 1
Showing max 1 results:
dirt

【问题讨论】:

  • 你得到了什么输出?
  • 我想问题是我没有得到任何输入,所以我不确定程序是否正常工作。
  • 我认为这意味着您也没有收到错误堆栈跟踪?
  • 是的,对不起,我也忘了提。

标签: python


【解决方案1】:

这是一个查找输入字符的字谜的函数的工作示例。您可以放入一个计数器并在需要时使用break 退出循环。我相信用户输入工作正常

dictionary_file = '/usr/share/dict/american-english' # Ubuntu's dictionary file

def anagrams(chars, dictionary_file):

    with open(dictionary_file) as f:

        # iterate through the dictionary file one line at a time
        for line in f:

            # Check to see that all characters are in there and the length matches
            if all(c in line for c in chars) and (len(line.strip()) == len(chars)):

                # Present the match
                print(line.strip())


anagrams('ritd', dictionary_file)
# dirt

如果您想捕获结果然后以其他方式处理它们,您可以将print() 更改为yield 并迭代生成器。 (这就像迭代 range(42)

def anagrams(chars, dictionary_file):

    with open(dictionary_file) as f:
        for line in f:
            if all(c in line for c in chars) and (len(line.strip()) == len(chars)):
                yield line.strip()


for match in anagrams('ritd', dictionary_file):
    print(match)
# dirt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 2018-01-16
    • 2017-07-18
    • 2018-04-05
    • 2021-12-04
    • 1970-01-01
    • 2019-06-02
    相关资源
    最近更新 更多