【问题标题】:Better logic for testing string contents测试字符串内容的更好逻辑
【发布时间】:2012-01-20 18:26:10
【问题描述】:

我有一个包含一些文本的 html 元素列表。我需要找到包含我要提供的所有单词的元素。我有一些代码可以完成我想要的,但我确信有更好的方法来做到这一点

myWords=['some', 'supplied','words']
theTextContents='a string that might or might not have all of some supplied words'
goodElements=[]
count=0
for word in myWords:
    if word in TheTextContents:
    count+=1
if count==len(myWords):
    goodElements.append(theTextContents)

还有很多代码,但这是我们测试 MyWords 中的所有单词是否都在 theTextContent 中的基本方法。在我看来,这太笨重了,不能成为好的 Python 代码

任何见解将不胜感激

【问题讨论】:

    标签: python coding-style logic


    【解决方案1】:
    if set(theTextContents.split()) >= set(myWords):
        ...
    

    【讨论】:

    • 感谢这非常干净和有用,我不会想到这一点,所以感谢您抽出宝贵时间提供此答案
    • 根据timeit OP 的数据最有效。
    【解决方案2】:
    if all(word in theTextContents.split() for word in myWords):
        ...
    

    all Python 2.5+ 中的函数

    【讨论】:

    • +1 但改进它:all(word in theTextContents.split(' ') for word in myWords)
    • @danihp:说得好,因为这甚至修复了原始版本中可能存在的错误。
    • 谢谢我不知道这一切都很棒
    【解决方案3】:

    尝试:

    myWords=['some', 'supplied','words']
    theTextContents='a string that might or might not have all of some supplied words'
    goodElements=[]
    
    splitted = theTextContents.split()
    if all(word in splitted for word in myWords):
        goodElements.append(theTextContents)
    

    【讨论】:

    • +1 在循环外分割文本(生成器表达式)是提高性能的好主意。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2010-12-24
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 2021-03-03
    相关资源
    最近更新 更多