【问题标题】:Testing input against dictionary (Python)根据字典测试输入(Python)
【发布时间】: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


【解决方案1】:

当您遇到此类问题时,一个好主意通常是查看您尝试比较的值。

例如:

for key in thesaurus:
    print(repr(key))

这表明键以\n 字符结尾。因此,它们不能出现在您的短语中。

尝试改用key.rstrip(),这是一种去除字符串右侧空格的方法。

【讨论】:

  • 我是否必须将文件作为字典打开才能将其中的文本用作键?或者我是怎么打开它的?
  • 您无法将文件作为字典打开。如果您愿意,可以将其作为列表读取并将该列表转换为字典,但我在这里看不到重点
猜你喜欢
  • 2022-07-29
  • 2021-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-13
  • 2012-07-24
  • 2021-02-28
  • 1970-01-01
相关资源
最近更新 更多