有没有办法使用列表中的正则表达式?

Is there a way to using reg expressions from a list?

我有一个主题词列表,包含正则表达式:

list = ['peaceful','thank\s?god','infuriated','mood\s?dropped']

以及主题词与其主题的字典映射列表:

dict = {'peaceful': 'Restful','thank\s?god': 'Thankful','infuriated': 'Angry','mood\s?dropped':'Sad'}

目标是写一个函数来判断一个字符串是否包含列表中的正则表达式,return到匹配的主题。

有可能某些提及可以与多个主题相匹配。所以 需要保留所有匹配的主题。此外,区分大小写是另一个需要考虑的问题。

我试过了:

import re
def topic_emotion(text):
    text_lower=text.lower()
    output = []
    for elem in Emotion_Keywords_list:
        if bool(re.search(elem, text_lower)):
            output.append(Emotion_dict[elem])
    return output

例如:

topic_emotion('todaypeacefulday Im INFURIATED') = ['Restful','Angry']

但似乎不对,无法处理正则表达式的情况,还有其他我应该考虑的因素吗?

以上代码在 Python 3.7

上运行良好

正则表达式模式涉及许多特殊字符。更好的方法是在使用前编译模式。

import regex as re

Emotion_Keywords_list = ['peaceful','thank\s?god','infuriated','mood\s?dropped']

主题 = ['Restful','Thankful','Angry','Sad']

进口重新 def topic_emotion(文字): 输出= [] compiled_keywords =[]

for elem in Emotion_Keywords_list:
    compiled_keywords.append(re.compile(elem,flags=re.I))

emotion_dict=dict(zip(compiled_keywords,topic))

for elem in compiled_keywords:
    if bool(re.search(elem, text)):
        output.append(emotion_dict[elem])
return output