python - 如何在 python 3.4 中预处理 yaml 文件?

标签 python python-3.x stream generator

背景是我有数百个 Yaml 文件,它们是系统的配置文件。我想对它们进行整体分析,寻找其配置中的问题。

所以我需要像这样预处理每个文件 this question在对它们进行某些操作之前删除一些非法字符。然而我是一个 python 新手,无法使用建议的生成器解决方案。如果可能的话,不应修改真实文件。我使用的是 python 3.4。

我的主要问题是迭代器函数没有被调用,这让我认为我没有正确访问迭代器行为。

本质上我有一个文件处理函数,可以处理目录中的所有文件,如下所示:

with open(os.path.join(myDir, fileName), 'r') as inputFile:
    print("about to call replace_iter")
    iterable = replace_iter(inputFile, "push", "force")
    print("about to call yaml.safe_load()")
    dataMap = yaml.safe_load(iterable)
    print("about to process my data map")
    type = dataMap['type']
    # process the dataMap ites ...
    print("done")

我在文件顶部定义了一个函数,如下所示

def replace_iter(iterable, search, replace):
    print("replace_iter called")
    for value in iterable:
        yield value.replace(search, replace)

这给出了这样的输出,跳过了对生成器函数的调用,因此它表明我没有正确访问迭代器功能。

about to call replace_iter
about to call yaml.safe_load()

最佳答案

str.replace不修改字符串,但返回修改后的值:

str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

您需要生成返回值。

def replace_iter(iterable, search, replace):
    for value in iterable:
        yield value.replace(search, replace)

关于python - 如何在 python 3.4 中预处理 yaml 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30600090/

相关文章:

python - python 中的 random.seed 函数如何处理单词?转换成什么数?

python - 类型错误 : concat() got multiple values for argument 'axis'

android - 使用 Android Management API 创建策略 - Quickstart Colab

ruby - Ruby 中有类似 null-stream 的东西吗?

python - Pandas 将重复值重新堆叠到列中

Python 主方法位置约定

python - 从元组列表中提取元组值

mysql - 无法通过 django 从 mysql 数据库执行并发请求; url 处出现接口(interface)错误 (0, '' )

html - 黑莓网站:支持HTML5

python - 将 h264 字节字符串转换为 OpenCV 图像