首页 > 解决方案 > 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

无论如何我可以通过打印匹配的单词来解决它吗?

标签: python

解决方案


看起来你需要正则表达式:

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

推荐阅读