[英]How can you use re.sub to replace the content of a capture group with a string?
[英]How do you replace only partial string with re.sub
假设我有文本:
text = 'Washington state Washington DC"
我希望我的新输出是
'WA state Washington DC'
我试过了
re.sub('Washington(\s[^DC])', 'WA ', text)
并获得以下输出,该输出除去“ state”的首字母:
'WA tate Washington DC'
基本上,我希望将“华盛顿”的每个实例都更改为“ WA”,只要它不在“ DC”之前。 我敢肯定有一种非常简单的方法可以做到这一点,而我的大脑今天根本就不喜欢工作! (我正在使用Python 3.x)请帮忙! 谢谢
像这样使用负前瞻:
Washington(?!\\s*DC)
它将检查华盛顿后面是否有任意数量的空格和“ DC”
谢谢你的提问。 它让我磨练了我相对较新的Python技能。 有很多方法可以做到这一点。 我喜欢这样:
import re
wa = "Washington state Washington DC"
regexp = r'Washington\s'
regexp1 = r'WA(\s+DC)'
text = re.sub(regexp, 'WA ', wa)
text2 = re.sub(regexp1, 'Washington DC', text)
print(text2)
基本上,它将所有出现的“华盛顿”更改为“ WA”,然后将所有出现的“ WA DC”更改为“华盛顿DC”。
您可以尝试以下方法:
import re
text = ["Washington state Washington DC", "the great state of Washington", "Lives in Washington DC", "I live in Washington State"]
new_text = [re.sub('Washington(?!\sDC)', 'WA', i) for i in text]
输出:
['WA state Washington DC', 'the great state of WA', 'Lives in Washington DC', 'I live in WA State']
测试用例:
text = {"Washington state Washington DC":"WA state Washington DC", "the great state of Washington":"the great state of WA", "Lives in Washington DC":"Lives in Washington DC", "I live in Washington State":"I live in WA State"}
for a, b in text.items():
assert re.sub('Washington(?!\sDC)', 'WA', a) == b, "failed"
print("passed")
输出:
passed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.