【问题标题】:I want to iterate trough a txt in python and change each word我想遍历python中的文本并更改每个单词
【发布时间】:2020-05-22 16:23:16
【问题描述】:

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

【问题讨论】:

  • 你能提供一个示例输出吗?
  • 好吧,如果你想“遍历每个单词”,那么首先你需要从文件中获取单词,是吗?您知道如何将字符串拆分为单个单词吗?
  • 你能发布一些示例输入/输出
  • 另外,请显示您尝试过的实际代码,而不是“类似”您的想法。例如,我假设您能够读取该文件,因为您获得了 some 类型的输出。而且我确定您实际上并没有写 return string(),因为该字符串不可调用。
  • 你为什么写这个dict[key]()。您的程序中有许多语法错误。

标签: python file dictionary


【解决方案1】:

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

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

【讨论】:

  • 谢谢,这真的很有帮助!我有另一个问题!如果 a.txt 中有一个单词不在字典中,我怎么能不从 b.txt 中包含它(比如删除它)?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-10
    • 2011-05-03
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多