首页 > 解决方案 > 小写除列表中的元素外的所有文本

问题描述

我有这样的文字:s = "I am Enrolled in a course, MPhil since 2014. I LOVE this SO MuCH."

和一个单词列表list = ["MPhil", "MuCH"]

我正在寻找一个能够小写除列表元素之外的所有文本的正则表达式代码。

我发现这个正则表达式解决方案能够小写除之间的单词之外的所有内容''

s = re.sub(r"\b(?<!')(\w+)(?!')\b", lambda match: match.group(1).lower(), s)

但我不知道如何把它变成我的案子。

我试图拆分文本并检查它是否来自列表,但我没有发现它真的很实用。

如果有人可以给我一个提示或建议我一些东西,我将不胜感激

标签: pythonregex

解决方案


只需查看您匹配的单词是否在要保持原样的单词集中:

import re

words_to_keep = {"MPhil", "MuCH"}


def replace_if_not_in_keeplist(match):
    word = match.group()
    if word in words_to_keep:
        return word
    return word.lower()


s = "I am Enrolled in a course, MPhil since 2014. I LOVE this SO MuCH."
s2 = re.sub(r"\w+", replace_if_not_in_keeplist, s)

print(s)
print(s2)

输出

I am Enrolled in a course, MPhil since 2014. I LOVE this SO MuCH.
i am enrolled in a course, MPhil since 2014. i love this so MuCH.

推荐阅读