你能用 Python 中的字典值写一个 str.replace() 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14156473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:37:37  来源:igfitidea点击:

can you write a str.replace() using dictionary values in Python?

pythondictionarystr-replace

提问by user1947457

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

我必须在地址字段中用 NS 替换北、南等。

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.

我知道我什至不接近!!但是,如果您可以使用这样的字典值,我们将不胜感激。

回答by sloth

You are probably looking for iteritems():

您可能正在寻找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)

address is now '123 N ANYWHERE STREET'

地址是现在 '123 N ANYWHERE STREET'



Well, if you want to preserve case, whitespace and nested words (e.g. Southstreetshould not converted to Sstreet), consider using this simple list comprehension:

好吧,如果您想保留大小写、空格和嵌套单词(例如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 is now

new_address 现在是

N 123 E Anywhere Southstreet    W

回答by Samuele Mattiuzzo

you are close, actually:

你很接近,实际上:

dictionary = {"NORTH":"N", "SOUTH":"S" } 
for key in dictionary.iterkeys():
    address.upper().replace(key, dictionary[key])

Note:for Python 3 users, you should use .keys()instead of .iterkeys():

注意:对于 Python 3 用户,您应该使用.keys()代替.iterkeys()

dictionary = {"NORTH":"N", "SOUTH":"S" } 
for key in dictionary.keys():
    address.upper().replace(key, dictionary[key])

回答by Adem ?zta?

Try,

尝试,

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)

回答by rich tier

address = "123 north anywhere street"

for word, initial in {"NORTH":"N", "SOUTH":"S" }.items():
    address = address.replace(word.lower(), initial)
print address

nice and concise and readable too.

很好,简洁,可读。

回答by Duncan

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'

回答by fralau

"Translating" a string with a dictionary is a very common requirement. I propose a function that you might want to keep in your toolkit:

用字典“翻译”一个字符串是一个非常普遍的要求。我提出了一个您可能希望保留在工具包中的函数:

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

Then you can write:

然后你可以写:

>>> a = {'hello':'bonjour', 'world':'tout-le-monde'}
>>> translate('hello world', a)
'bonjour tout-le-monde'

回答by Anna

All of these answers are good, but you are missing python string substitution - it's simple and quick, but requires your string to be formatted correctly.

所有这些答案都很好,但是您缺少 python 字符串替换 - 它简单快捷,但要求您的字符串格式正确。

address = "123 %(direction)s anywhere street"
print(address % {"direction": "N"})

回答by ahuigo

Both using replace()and format()are not so precise:

使用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

It is better to translate with re.sub()if you need precise place:

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)

回答by Artem Malikov

def replace_values_in_string(text, args_dict):
    for key in args_dict.keys():
        text = text.replace(key, str(args_dict[key]))
    return text

回答by Trafalgar

I would suggest to use a regular expression instead of a simple replace. With a replace you have the risk that subparts of words are replaced which is maybe not what you want.

我建议使用正则表达式而不是简单的替换。通过替换,您可能会面临替换单词子部分的风险,这可能不是您想要的。

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)