python - 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
无论如何我可以通过打印匹配的单词来解决它吗?
解决方案
看起来你需要正则表达式:
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
推荐阅读
- sql-server - 如何将包含文件流的 SQL Server 数据库从一台服务器附加到另一台服务器
- reactjs - Material UI - Stepper 组件 - 异步图标
- vba - VBA - 如何在Visual Basic中的一个字段中选择多个值进行应用?
- javascript - ReactJS 和 material-ui 没有在移动设备上呈现页面的整个宽度
- node.js - 如何允许任何用户使用 youtube API 在我的 youtube 频道中上传视频?
- java - 文件未在 Java 中删除
- parsing - JCup 中的错误恢复。块末尾缺少分号
- python - 在 python 多线程中创建线程
- django - 是否有用于运行 Celery worker 的 Django manage.py 命令?
- flutter - Flutter Build - Gradle 任务 assembleDebug 失败,退出代码为 1