欢迎来到 岁月小筑

Python使用字典进行字符串的替换

前言

昨天在折腾一点小玩意,需要用到百度翻译,但是有些名词用翻译确实很蛋疼,想来想去,最后决定先自行替换,不能替换再翻译。

代码是从gg搜到的,感觉十分不错,就抄录下来了

Python代码

以下是替换函数,直接扔到代码里面就好:

def keymap_replace(
        string: str, 
        mappings: dict,
        lower_keys=False,
        lower_values=False,
        lower_string=False,
    ) -> str:
    """Replace parts of a string based on a dictionary.

    This function takes a string a dictionary of
    replacement mappings. For example, if I supplied
    the string "Hello world.", and the mappings 
    {"H": "J", ".": "!"}, it would return "Jello world!".

    Keyword arguments:
    string       -- The string to replace characters in.
    mappings     -- A dictionary of replacement mappings.
    lower_keys   -- Whether or not to lower the keys in mappings.
    lower_values -- Whether or not to lower the values in mappings.
    lower_string -- Whether or not to lower the input string.
    """
    replaced_string = string.lower() if lower_string else string
    for character, replacement in mappings.items():
        replaced_string = replaced_string.replace(
            character.lower() if lower_keys else character,
            replacement.lower() if lower_values else replacement
        )
    return replaced_string

使用方法:

str=keymap_replace('要替换的字符串',{'替换':'修改'})

#替换后

print(str)

#'要修改的字符串'

更详细的使用方法,原作者已经写在代码中了~

点赞

发表评论

电子邮件地址不会被公开。