繁体   English   中英

使用嵌套和/或与 in/not in 运算符一起在给定文本中查找单词

[英]Finding a word in given text using nested and/or along with in/not in operators

嗨,我有一个字符串,我试图在找到某个条件时打印一些消息。 我正在使用的代码 -

text = """The nearest paid public fire department 24/7 is located 1km"""

if ((("public" in text.lower()) or ("Public" in text.lower()))
    and (("fire department" in text.lower()))
    and (("full time" not in text.lower()) or ("full-time" not in text.lower()) or ("24/7" not in text.lower()))):
     print("Keyword not present in text")
else:
     print("Keyword present")

Output - Keyword not present in text

输出是错误的,因为文本中存在 24/7,理想情况下它应该打印“关键字存在”。

我无法拆分句子然后尝试查找单词,因为我想查找提到的某些单词。 例如“消防部门”。

你能建议我哪里出错了。

text = """The nearest full-time full time paid public fire department 24/7 is located 1km"""

expected = ["public", "fire department", "24/7"]

if any(s not in text.lower() for s in expected):
    print("Key words missing")
else:
    print("Keywords present")

一种更简单的方法来实现您的结果,而不是没有很多布尔比较。

如果您想验证不应该是文本一部分的几个子字符串


expected = ["public", "fire department", "24/7"]
unexpected = ["full-time","full time"]

if any(s not in text.lower() for s in expected) or any(s in text.lower() for s in unexpected):
    print("Key words missing")
else:
    print("Keywords present")

if 条件的第一部分验证文本中是否存在所有预期的子字符串。 条件的第二部分验证文本中不存在任何意外子字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM