背景是我有数百个 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/