我当前的程序遇到了麻烦,该程序应该从用户输入中提取字母,对照我已有的字典文件检查它们,然后返回可以由一系列字母组成的可能的单词。然后,应该由用户输入来指示实际返回了多少个单词。我是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
答案 0 :(得分:0)
这是查找输入字符的字谜的函数的有效示例。您可以放入一个计数器,并在需要时使用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