【发布时间】:2016-05-07 22:02:44
【问题描述】:
我正在尝试将用户输入的短语与我已导入程序的文件(字典)进行比较。我的代码是:
thesaurus = open("thesaurus.txt", "r")
phrase = input("Enter a phrase: ")
for key in thesaurus:
if key in phrase:
print ("hello")
我已经通过输入我知道在文件中的短语来测试它,所以我应该在某些点打印“你好”,但我的程序没有返回任何内容。我想问题出在我设置的 for 循环上。
感谢任何帮助,谢谢!
编辑:
counter = 0
for key in thesaurus:
counter = 0
for x in range(0, len(phrase)):
if phrase[counter] == key.rstrip():
print ("hi")
counter += 1
【问题讨论】:
-
大小写一致吗?
-
key将包含一个新行。你应该改用key.rstrip()。 -
@zondo key.rstrip() 一旦我进入 for 循环?
-
@DannyGarcia:是的:
if key.rstrip() in phrase: -
@zondo 似乎它仍在使用 .rstrip() 做同样的事情。我在上面添加了一个编辑过的代码,你认为这是一种更好的方法吗? (即使使用新代码,它仍然在做同样的事情)
标签: python loops for-loop dictionary