租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

python怎么批量替换文本内容,python批量替换txt指定内容

发布时间:2024-05-27 18:42:08

python怎样批量替换文本内容

在Python中,可使用re模块来实现批量替换文本内容。下面是一个简单的示例代码:

import re

def batch_replace_text(input_text, replacements):
    for old_str, new_str in replacements.items():
        input_text = re.sub(old_str, new_str, input_text)
    return input_text

if __name__ == "__main__":
    text = "Hello, world! This is a test text for batch replacement."
    replacements = {
        r"Hello": "Hi",
        r"world": "Python",
        r"test": "example"
    }
    
    new_text = batch_replace_text(text, replacements)
    print(new_text)

在上面的示例中,batch_replace_text函数接收一个输入文本input_text和一个包括需要替换的字符串及替换后的新字符串的字典replacements。然后使用re.sub函数来实现批量替换文本内容。最后输出替换后的新文本。