你可以用Python中的字典值写一个str.replace()吗? [英] can you write a str.replace() using dictionary values in Python?

查看:540
本文介绍了你可以用Python中的字典值写一个str.replace()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果我有



我必须在地址字段中用NS替换北,南等。 pre> list = {'NORTH':'N','SOUTH':'S','EAST':'E','WEST':'W'}
address =123 north anywhere street

我可以迭代我的字典值来替换我的地址字段


 在列表[]中的dir:
address.upper()。replace(key,value)

我知道我还没有关闭!但是,如果您可以使用这样的字典值,任何输入都将不胜感激。

解决方案

一个选项我不认为任何人还没有建议是构建一个包含所有键的正则表达式,然后只需在字符串上进行一次替换:

 >> > import re 
>>> l = {'NORTH':'N','SOUTH':'S','EAST':'E','WEST':'W'}
>> pattern ='|'.join(sort(re.escape(k)for l in))
>>>> address =123 north anywhere street
>>>> re.sub(pattern,lambda m:l.get(m.group(0).upper()),address,flags = re.IGNORECASE)
'123 N any street'
>> ;>

这样做的优点是正则表达式可以忽略输入字符串的大小写而不进行修改。 / p>

如果您只想使用完整的字词操作,那么您也可以通过简单的模式修改来执行此操作:

 >>> pattern = r'\b({})\b'.format('|'.join(在(l)中对于k的sort(re.escape(k)))
>>> address2 =123 north anywhere southstreet
>>> re.sub(pattern,lambda m:l.get(m.group(0).upper()),address2,flags = re.IGNORECASE)
'123 N任何地方southstreet'


I have to replace the north, south, etc with N S in address fields.

If I have

list = {'NORTH':'N','SOUTH':'S','EAST':'E','WEST':'W'}
address = "123 north anywhere street"

Can I for iterate over my dictionary values to replace my address field?

for dir in list[]:
   address.upper().replace(key,value)

I know i'm not even close!! But any input would be appreciated if you can use dictionary values like this.

解决方案

One option I don't think anyone has yet suggested is to build a regular expression containing all of the keys and then simply do one replace on the string:

>>> import re
>>> l = {'NORTH':'N','SOUTH':'S','EAST':'E','WEST':'W'}
>>> pattern = '|'.join(sorted(re.escape(k) for k in l))
>>> address = "123 north anywhere street"
>>> re.sub(pattern, lambda m: l.get(m.group(0).upper()), address, flags=re.IGNORECASE)
'123 N anywhere street'
>>> 

This has the advantage that the regular expression can ignore the case of the input string without modifying it.

If you want to operate only on complete words then you can do that too with a simple modification of the pattern:

>>> pattern = r'\b({})\b'.format('|'.join(sorted(re.escape(k) for k in l)))
>>> address2 = "123 north anywhere southstreet"
>>> re.sub(pattern, lambda m: l.get(m.group(0).upper()), address2, flags=re.IGNORECASE)
'123 N anywhere southstreet'

这篇关于你可以用Python中的字典值写一个str.replace()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆