首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找python中的文本中是否存在单词的逻辑

查找python中的文本中是否存在单词的逻辑
EN

Stack Overflow用户
提问于 2019-07-25 17:23:52
回答 2查看 91关注 0票数 1

我有一个字符串和一个单词列表,我想检查它们是否存在于给定的文本字符串中。我正在使用下面的logic.....is来优化它:

代码语言:javascript
复制
import re
text="""
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make
it very attractive for Rapid Application Development"""
tokens_text=re.split(" ",text)
list_words=["programming","Application"]
if (len(set(list_words).intersection(set(tokens_text)))==len(list_words)):
    print("Match_Found")
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-07-25 17:29:30

使用set.issubset(other)操作:

代码语言:javascript
复制
text="""
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make
it very attractive for Rapid Application Development"""
tokens = text.split()
list_words = ["programming", "Application"]

if (set(list_words).issubset(set(tokens))):
    print("Match_Found")

或者简单地使用all函数:

代码语言:javascript
复制
if all(x in tokens for x in list_words):
    print("Match_Found")
票数 1
EN

Stack Overflow用户

发布于 2019-07-25 17:30:20

你可以使用python的in运算符,我不知道它是不是更快。

代码语言:javascript
复制
str = "Messi is the best soccer player"

"soccer" in str
-> True

"football" in str
-> False
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57198547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档