Python:打印条件

时间:2019-07-10 08:18:43

标签: python

我发现几分钟前我刚刚问错了一个问题,对此感到抱歉。我运行了一个代码,该代码需要确定特定位置的单词是否符合我的条件。

原始代码不是英语,我只是尝试使用一种简单的方法向您展示我遇到的问题。我的语言中的单词之间实际上没有空格,因此使用split或re无效。

我需要在“汽车”之前找到一个词,以了解某人是否爱汽车。因此,我使用位置作为识别它的条件。

例如:(但是太长了)

message="I do not like cars."

#print(message[14:18])  #cars starts from location 14
location = 14

if message[int(loca)-5:int(loca)-1]=="like":
    print("like")
elif message[int(loca)-8:int(loca)-1]=="dislike":
    print("dislike")
elif message[int(loca)-5:int(loca)-1]=="hate":
    print("hate")
elif message[int(loca)-5:int(loca)-1]=="cool":
    print("cool")

我实际上在代码中使用了此代码,但发现我无法打印该单词:

if (
    message[int(location) - 5:int(location) - 1] == "like" or
    message[int(location) - 8:int(location) - 1] == "dislike" or
    message[int(location) - 5:int(location) - 1] == "hate" or
    message[int(location) - 5:int(location) - 1] == "cool"
):
    #print "like"
    #unable to do it

反正我可以通过打印匹配的单词来解决它吗?

1 个答案:

答案 0 :(得分:2)

好像您需要正则表达式:

import re

message="I do not dislike cars."
check_list = {"like", "dislike", "hate", "cool"}
pattern = re.compile(r"(\b{}\b)".format("|".join(check_list))) #or re.compile(r"({})".format("|".join(check_list)))


m = pattern.search(message)
if m:
    print(m.group(1))  # --> dislike