我有一个方法(.yml解析器)将输入流作为输入.问题是当它在某些地方遇到某些字符时会抛出错误,例如%.
我想要做的是获取流,用%占位符替换所有,然后将其传递给解析器.
这就是我所拥有的(当前输入不起作用):
stream = open('file.yml', 'r')
dict = yaml.safe_load(stream)
Run Code Online (Sandbox Code Playgroud)
但我认为我需要的是:
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)
Run Code Online (Sandbox Code Playgroud)
这样做的一个好方法是编写一个生成器,这样它仍然是懒惰的(整个文件不需要立即读入):
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)
Run Code Online (Sandbox Code Playgroud)
注意使用该io.TextIOBase语句打开文件 - 这是在Python中打开文件的最佳方式,因为它确保文件正确关闭,即使发生异常时也是如此.
另请注意,这io.StringIO是一个糟糕的变量名称,因为它会粉碎内置的with并阻止您使用它.
请注意,您的dict功能基本上是dict(),而且stringFromStream()是file.read().你称之为'stream'的实际上只是字符串上的迭代器(文件的行).