python - 小写除列表中的元素外的所有文本
问题描述
我有这样的文字: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)
但我不知道如何把它变成我的案子。
我试图拆分文本并检查它是否来自列表,但我没有发现它真的很实用。
如果有人可以给我一个提示或建议我一些东西,我将不胜感激
解决方案
只需查看您匹配的单词是否在要保持原样的单词集中:
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.
推荐阅读
- php - 从表中获取空值
- haskell - Haskell 左箭头运算符替代
- reactjs - 根据 if 语句返回网页布局
- docker - Docker image failed with caniuse-lite is outdated 错误
- angular - 从依赖于 forkJoined 请求之一的 forkJoin 中发出请求的 rxjs 方式
- django - 删除具有相同模型的子对象的对象时,Django 出现 post_delete 信号问题
- r - 在字符串 R 上粘贴字母索引
- angular - 获取 Observable 和 Behavior Subject 的最新值
- javascript - 无法在组件外部获取 redux 状态
- python - 如何在 python 中为 copula (copulafit) 复制 matlab 模型