【问题标题】:Picking phrases containing specific words in python在python中挑选包含特定单词的短语
【发布时间】:2020-03-21 13:21:57
【问题描述】:

我有一个包含 10 个名称的列表和一个包含许多短语的列表。我只想选择包含其中一个名称的短语。

ArrayNames = [Mark, Alice, Paul]
ArrayPhrases = ["today is sunny", "Paul likes apples", "The cat is alive"]

在示例中,考虑到包含 Paul 的面孔,考虑到这两个数组,有没有办法只选择第二个短语? 这是我尝试过的:

def foo(x,y):
tmp = []
for phrase in x:
    if any(y) in phrase:
        tmp.append(phrase)     
print(tmp)

x 是短语数组,y 是名称数组。 这是输出:

    if any(y) in phrase:
TypeError: coercing to Unicode: need string or buffer, bool found

我非常不确定我使用的有关 any() 构造的语法。有什么建议吗?

【问题讨论】:

    标签: python if-statement syntax any


    【解决方案1】:

    您对any的用法不正确,请执行以下操作:

    ArrayNames = ['Mark', 'Alice', 'Paul']
    ArrayPhrases = ["today is sunny", "Paul likes apples", "The cat is alive"]
    
    result = []
    for phrase in ArrayPhrases:
        if any(name in phrase for name in ArrayNames):
            result.append(phrase)
    
    print(result)
    

    输出

    ['Paul likes apples']
    

    你得到一个TypeError,因为 any 返回一个布尔值并且你试图在字符串中搜索一个布尔值 (if any(y) in phrase:)。

    注意any(y) 有效,因为它将使用y 的每个字符串的truthy 值。

    【讨论】:

    • 现在可以了,但是您认为这是最有效的方法吗?我必须扫描整个文档,是否需要我的脚本尽可能高效。我愿意接受不同的解决方案!
    • @IanWing 来加速您需要使用特定数据结构(可能是 trie)的事情,但这是一个不同的问题。我建议你查一下 flashtext
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    相关资源
    最近更新 更多