【问题标题】:YAML find and replace text PythonYAML 查找和替换文本 Python
【发布时间】:2021-01-14 14:19:41
【问题描述】:

我有一些 YAML 格式的文件,我需要在 $title 文件中找到文本并替换为我指定的内容。配置文件大概是什么样子:

JoinGame-MOTD:
  Enabled: true
  Messages:
  - '$title'

YAML 文件可能看起来不同,所以我想制作一个通用代码,它不会获取任何特定字符串,而是将所有 $title 替换为我指定的内容

我想做什么:

import sys
import yaml

with open(r'config.yml', 'w') as file:
    
    def tr(s):
        return s.replace('$title', 'Test')

        yaml.dump(file, sys.stdout, transform=tr)

请帮助我。没有必要使用我的代码,我会对任何适合我的示例感到满意

【问题讨论】:

  • 那么,您的代码如何为您工作?有什么需要改进的吗?
  • 看看this question,也许它的答案可能会有所帮助
  • 您有任何错误吗?如果是这样,你能告诉我们哪些吗?
  • @Axiumin_ 否,但之后文件完全为空

标签: python yaml


【解决方案1】:

完全不使用 yaml 包可能更容易。

with open("file.yml", "r") as fin:
     with open("file_replaced.yml", "w") as fout:
         for line in fin:
             fout.write(line.replace('$title', 'Test'))

编辑:

就地更新

with open("config.yml", "r+") as f:
    contents = f.read()
    f.seek(0)
    f.write(contents.replace('$title', 'Test'))
    f.truncate()

【讨论】:

  • 它有效,谢谢。是否可以在文件中进行更改并将它们保存到同一个文件中,以免创建副本?
  • 已编辑到位
【解决方案2】:

您还可以一次读取和写入数据。 os.path.join 是可选的,它确保 yaml 文件是相对于您的脚本存储路径读取的

import re
import os

with open(os.path.join(os.path.dirname(__file__), 'temp.yaml'), 'r+') as f:
    data = f.read()
    f.seek(0)
    new_data = data.replace('$title', 'replaced!')
    f.write(new_data)
    f.truncate()

如果您希望动态替换除$title 之外的其他关键字,例如$description$name,您可以使用这样的正则表达式编写函数;

def replaceString(text_to_search, keyword, replacement):
    return re.sub(f"(\${keyword})[\W]", replacement, text_to_search)

replaceString('My name is $name', '$name', 'Bob')

【讨论】:

    猜你喜欢
    • 2022-07-13
    • 1970-01-01
    • 2019-07-30
    • 2013-05-27
    • 2011-08-20
    • 2011-11-24
    • 2021-10-25
    • 2020-08-23
    • 2011-06-12
    相关资源
    最近更新 更多