0

我试图让程序检查用户输入的“起床”或“起床”,然后让它打印“我起来”​​。问题是它不会打印“im up”,而是直接进入 else 语句。我现在拥有的这段代码使它成为如果我将“起床”更改为“你好”的地方,那么如果我要在输入中输入任何内容并在输入中包含“你好”,它将打印“测试”,我会如果可能的话,喜欢保持这种状态吗?代码:

dic = {"get,up", "rise,and,shine"}
test = raw_input("test: ")
tokens = test.split()
if dic.intersection(tokens):
    print "test"
else:
    print "?" 

帮助表示赞赏。

4

1 回答 1

2

dic.intersection()返回两个集合的交集。例如:

{1, 2, 3}.intersection({2, 3, 4})  # {2, 3}

您可能只想测试成员资格:

if tokens in dic:
    ...

虽然这也行不通,因为你用空格分割字符串,这将使它测试单个单词,而不是整个短语。此外,命名你的集合dic也不是一个好主意。这是一个集合,而不是字典。

简而言之,不要使用集合,也不要使用.split()

phrases = ['get up', 'rise and shine']
phrase = raw_input('Enter a phrase: ')

if phrase in phrases:
    print "test"
else:
    print "?" 
于 2013-06-18T00:37:30.843 回答