溫馨提示×

python怎么批量替換文本內容

小億
215
2024-05-27 18:42:08
欄目: 編程語言

在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函數來實現批量替換文本內容。最后輸出替換后的新文本。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女