gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:31:03 25 4
gpt4 key购买 nike

我有一个字符串和一个单词列表,我想检查它们是否出现在给定的文本字符串中。我正在使用以下逻辑......还有其他方法可以优化它吗:-

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")

最佳答案

set.issubset(other)操作:

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函数:

if all(x in tokens for x in list_words):
print("Match_Found")

关于python - 在Python中查找文本中是否存在单词的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57198547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com