我想在python中通过txt进行迭代并更改每个单词

2024-05-15 20:37:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为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()

Tags: thekeytxtstringdictionarynot结构dict
2条回答

一种非常简单的方法是读取文件中的每一行并使用字典替换

d = {'old': 'new'}
new_lines = []
with open('a.txt') as f:
    lines = f.readlines()
    for line in lines:
        for key, value in d.items():
            new_lines.append(line.replace(key, value))

with open('b.txt', 'w') as f:
    f.writelines(new_lines)

注意:-这将把行old is gold转换为new is gnew。因此,您可能需要将行进一步拆分为单词,然后匹配整个单词进行替换并相应地保存

使用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))

相关问题 更多 >