替换流中的某些字符
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了替换流中的某些字符相关的知识,希望对你有一定的参考价值。
我有一个方法(.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)
答案
这样做的一个好方法是编写一个生成器,这样它仍然是懒惰的(整个文件不需要立即读入):
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'的实际上只是字符串上的迭代器(文件的行)。
以上是关于替换流中的某些字符的主要内容,如果未能解决你的问题,请参考以下文章