我正在尝试编写词汇游戏。
我正在使用正则表达式来隐藏我的单词,我不得不猜测。我对正则表达式使用的语法不满意-除了简单的示例,我非常困惑。
以动词为例
'to crank (sth) up'
我想将其转换为:
to _ _ _ _ _ (sth) _ _
该程序将从词汇表CSV文件中获取。我的约定是添加(sth)
或(smb)
用于及物动词。我不想在方括号之间隐藏这些位。同样,我也不想隐藏to
表示不定式的。
到目前为止,我正在应用的转换是:
chosen_word = "to crank (sth) up"
# To make the space between words double for better legibility
hidden_word = re.sub("\s", " ", chosen_word)
# To hide the letters of the word
hidden_word = re.sub("[a-z]", "_ ", hidden_word)
但这导致:
_ _ _ _ _ _ _ ( _ _ _ ) _ _
如何编码re.sub()
将_
除模式to
和 sth
和之外的所有字母字符转换为的方法smb
?
您可以捕获排除项,然后使用动态替换模式:
hidden_word = re.sub(r"(\bto\b|\(s(?:th|b)\))|[a-z]", lambda x: x.group(1) or "_ ", hidden_word)
请参阅Python演示。正则表达式详细信息:
(\bto\b|\(s(?:th|b)\))
-第1组:要么整个单词to
或(sth)
或(sb)
|
- 要么[a-z]
-小写ASCII字母lambda x: x.group(1) or "_ "
-匹配项将替换为第1组的值(如果已匹配),否则将替换为下划线加空格。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句