我想在python中遍历txt并更改每个单词

时间:2020-05-22 16:23:16

标签: python file dictionary

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

2 个答案:

答案 0 :(得分:0)

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

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。因此,您可能希望将行进一步分成单词,然后匹配整个单词以进行替换并相应保存

答案 1 :(得分:0)

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