我必须在地址栏中用N S替换北,南等。
如果我有
list = {'NORTH':'N','SOUTH':'S','EAST':'E','WEST':'W'}
address = "123 north anywhere street"
我可以迭代我的字典值来替换我的地址字段吗?
for dir in list[]:
address.upper().replace(key,value)
我知道我甚至不是很亲密!但是,如果您可以使用这样的字典值,那么任何输入都会受到赞赏。
答案 0 :(得分:12)
address = "123 north anywhere street"
for word, initial in {"NORTH":"N", "SOUTH":"S" }.items():
address = address.replace(word.lower(), initial)
print address
美观,简洁,可读。
答案 1 :(得分:3)
你很亲密,实际上:
dictionary = {"NORTH":"N", "SOUTH":"S" }
for key in dictionary.iterkeys():
address.upper().replace(key, dictionary[key])
注意:对于Python 3用户,您应该使用.keys()
代替.iterkeys()
:
dictionary = {"NORTH":"N", "SOUTH":"S" }
for key in dictionary.keys():
address.upper().replace(key, dictionary[key])
答案 2 :(得分:2)
我认为没有人建议的一个选项是构建一个包含所有键的正则表达式,然后只需对字符串进行一次替换:
>>> 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'
>>>
这样做的好处是,正则表达式可以忽略输入字符串的情况而不修改它。
如果您只想对完整的单词进行操作,那么您也可以通过简单修改模式来实现:
>>> 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'
答案 3 :(得分:2)
"翻译"带字典的字符串是一个非常常见的要求。我提出了一个您可能希望保留在工具箱中的函数:
def translate(text, conversion_dict, before=None):
"""
Translate words from a text using a conversion dictionary
Arguments:
text: the text to be translated
conversion_dict: the conversion dictionary
before: a function to transform the input
(by default it will to a lowercase)
"""
# if empty:
if not text: return text
# preliminary transformation:
before = before or str.lower
t = before(text)
for key, value in conversion_dict.items():
t = t.replace(key, value)
return t
然后你可以写:
>>> a = {'hello':'bonjour', 'world':'tout-le-monde'}
>>> translate('hello world', a)
'bonjour tout-le-monde'
答案 4 :(得分:1)
您可能正在寻找iteritems()
:
d = {'NORTH':'N','SOUTH':'S','EAST':'E','WEST':'W'}
address = "123 north anywhere street"
for k,v in d.iteritems():
address = address.upper().replace(k, v)
地址现在是'123 N ANYWHERE STREET'
好吧,如果你想保留大小写,空格和嵌套的单词(例如Southstreet
不应该转换为Sstreet
),请考虑使用这个简单的列表理解:
import re
l = {'NORTH':'N','SOUTH':'S','EAST':'E','WEST':'W'}
address = "North 123 East Anywhere Southstreet West"
new_address = ''.join(l[p.upper()] if p.upper() in l else p for p in re.split(r'(\W+)', address))
new_address现在是
N 123 E Anywhere Southstreet W
答案 5 :(得分:1)
所有这些答案都很好,但你缺少python字符串替换 - 它简单快捷,但要求你的字符串格式正确。
address = "123 %(direction)s anywhere street"
print(address % {"direction": "N"})
答案 6 :(得分:1)
def replace_values_in_string(text, args_dict):
for key in args_dict.keys():
text = text.replace(key, str(args_dict[key]))
return text
答案 7 :(得分:0)
尝试,
import re
l = {'NORTH':'N','SOUTH':'S','EAST':'E','WEST':'W'}
address = "123 north anywhere street"
for k, v in l.iteritems():
t = re.compile(re.escape(k), re.IGNORECASE)
address = t.sub(v, address)
print(address)
答案 8 :(得分:0)
使用replace()
和format()
都不那么精确:
data = '{content} {address}'
for k,v in {"{content}":"some {address}", "{address}":"New York" }.items():
data = data.replace(k,v)
# results: some New York New York
'{ {content} {address}'.format(**{'content':'str1', 'address':'str2'})
# results: ValueError: unexpected '{' in field name
如果您需要精确的地点,最好使用re.sub()
进行翻译:
import re
def translate(text, kw, ignore_case=False):
search_keys = map(lambda x:re.escape(x), kw.keys())
if ignore_case:
kw = {k.lower():kw[k] for k in kw}
regex = re.compile('|'.join(search_keys), re.IGNORECASE)
res = regex.sub( lambda m:kw[m.group().lower()], text)
else:
regex = re.compile('|'.join(search_keys))
res = regex.sub( lambda m:kw[m.group()], text)
return res
#'score: 99.5% name:%(name)s' %{'name':'foo'}
res = translate( 'score: 99.5% name:{name}', {'{name}':'foo'})
print(res)
res = translate( 'score: 99.5% name:{NAME}', {'{name}':'foo'}, ignore_case=True)
print(res)
答案 9 :(得分:0)
我建议使用正则表达式而不是简单的替换。替换后,您就有替换单词的子部分的风险,这也许不是您想要的。
import json
import re
with open('filePath.txt') as f:
data = f.read()
with open('filePath.json') as f:
glossar = json.load(f)
for word, initial in glossar.items():
data = re.sub(r'\b' + word + r'\b', initial, data)
print(data)