首页 > 解决方案 > 我想在 python 中遍历一个 txt 并更改每个单词

问题描述

我有一个名为的结构dictionary,它看起来像这样:

dictionary = {"The" : "A", "sun": "nap", "shining" : "süt", 
                 "wind": "szél", "not" : "nem", "blowing" : "fúj"}

我想遍历 .txt 并将每个单词更改为其密钥对并将其推送到新的 txt。

我的想法是这样的,但它只是返回值:

dict = {"The" : "A", "sun": "nap", "shining" : "süt", "wind" : "szél", "not" : "nem", "blowing" : "fúj"}
def translate(string, dict):
    for key in dict:
        string = string.replace(key, dict[key]())
    return string()

标签: pythonfiledictionary

解决方案


用于re避免重叠替换。该模式是从转义键构建的,替换字符串使用 lambda 表达式动态映射。

import re

table = {"The": "A", "sun": "nap", "shining": "süt", "wind": "szél", "not": "nem", "blowing": "fúj"}


def translate(string, mapping):
    pattern = r'(' + r'|'.join(re.escape(k) for k in mapping.keys()) + r')'
    return re.sub(pattern, lambda m: mapping[m.group(1)], string)


print(translate('The sun is not blowing wizd', table))

推荐阅读