替换流中的某些字符

时间:2013-01-18 14:31:05

标签: python stream

我有一个方法(.yml解析器),它将输入流作为输入。问题是当它在某些地方遇到某些字符时会抛出错误,例如%

我想要做的是获取流,用占位符替换所有%,然后将其传递给解析器。

这就是我所拥有的(当前输入不起作用):

    stream = open('file.yml', 'r')
    dict = yaml.safe_load(stream)

但我认为我需要的是:

    stream = open('file.yml', 'r')
    temp_string = stringFromString(stream)     #convert stream to string
    temp_string.replace('%', '_PLACEHOLDER_')  #replace with place holder
    stream = streamFromString(temp_String)     #conver back to stream
    dict = yaml.safe_load(stream)

1 个答案:

答案 0 :(得分:7)

这样做的好方法是编写一个生成器,这样它仍然是懒惰的(整个文件不需要立即读入):

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

with open("file.yml", "r") as file:
    iterable = replace_iter(file, "%", "_PLACEHOLDER")
    dictionary = yaml.safe_load(iterable)

请注意使用with语句打开文件 - 这是在Python中打开文件的最佳方式,因为它可以确保文件正常关闭,即使发生异常也是如此。

另请注意,dict是一个糟糕的变量名称,因为它会粉碎内置的dict()并阻止您使用它。

请注意,您的stringFromStream()功能基本上是file.read()steamFromString()data.splitlines()。你所谓的'stream'实际上只是字符串上的迭代器(文件的行)。

相关问题