【问题标题】:Logic to find if words are present in text in python查找python文本中是否存在单词的逻辑
【发布时间】:2019-07-25 09:23:51
【问题描述】:

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

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

【问题讨论】:

    标签: python pandas python-2.7 text nlp


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      可以用python的in操作符,不知道是不是更快。

      str = "Messi is the best soccer player"
      
      "soccer" in str
      -> True
      
      "football" in str
      -> False
      

      【讨论】:

      • 这将花费更多时间,因为它将在每个元素的 for 循环中。我还想检查列表中的这两个词是否都存在于文本中。我认为在那种情况下它不会有帮助..
      • 是的,你也会循环搜索字符串,祝你好运:)
      猜你喜欢
      • 1970-01-01
      • 2012-11-09
      • 2011-04-09
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 2018-04-01
      • 2013-02-02
      • 1970-01-01
      相关资源
      最近更新 更多