【问题标题】:Regular expressions - Creating a list by words extraction from text正则表达式 - 通过从文本中提取单词来创建列表
【发布时间】:2023-02-16 01:28:05
【问题描述】:

Example:

myList = []
text = ["salmonella in black pepper from brazil", "aflatoxins in fish from germany", "pseudomonas in meat from italy"]
findmatches = re.compile(r"\b" +
                         r"\b|\b".join(re.escape(hazard) for hazard in hazards_set) +
                         r"\b")

for i in text:
    for possible_match in set(findmatches.findall(i)):
        if possible_match in hazards_set:
            myList.append(possible_match)
    myList.append("")

print(myList)

This is what I get: ['salmonella', '', 'aflatoxins', '', '']

This is what I would like to get: ['salmonella','aflatoxins', ''] since "pseudomonas" is not in the set hazards_set.

How can I solve the problem?

标签: python


【解决方案1】:

使用.isdisjoint()为第一个for-loop设置if条件

for i in text:
    for possible_match in set(findmatches.findall(i)):
        if possible_match in hazards_set:
            myList.append(possible_match)
    if set(findmatches.findall(i)).isdisjoint(hazards_set): 
        myList.append("")

print(myList)

【讨论】:

    猜你喜欢
    • 2013-02-03
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    相关资源
    最近更新 更多