我有一个名为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()
一种非常简单的方法是读取文件中的每一行并使用字典替换
注意:-这将把行
old is gold
转换为new is gnew
。因此,您可能需要将行进一步拆分为单词,然后匹配整个单词进行替换并相应地保存使用
re
避免重复替换。模式是从转义键构建的,替换字符串是使用lambda表达式动态映射的相关问题 更多 >
编程相关推荐