我有一本包含一些值的字典
color=[black, white,....]
一个有很多包含多个这种颜色的字符串(在一个数组中),我需要将它们替换为字母C。因此,例如
"this is a phrase and it contains Blue"
一定是
"this is a phrase and it contains C"
我还需要小写颜色...(在字典中,首字母大写。
这是我的代码,但效果不佳
for item in json_data:
count_tot=count_tot+1;
for color in attributes_dictionary:
if color in item["title"]:
item["title"]=item["title"].replace(color,"{"+color+"}\_C")
print(item["title"])
只需使用颜色|
分隔符将颜色列表中的所有元素连接起来,然后将其作为正则表达式传递给re.sub
函数。(?i)
有助于进行不区分大小写的匹配,并\b
有助于匹配确切的单词。
import re
color=['black', 'white', 'Blue']
s = "this is a phrase and it contains Blue"
print re.sub(r'(?i)\b(?:'+'|'.join(color)+r')\b', 'C', s)
要获得注释中提到的输出,您需要使用捕获组。
print re.sub(r'(?i)\b('+'|'.join(color)+r')\b', r'{\1}_C', s)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句