YAML specification明確指出,YAML流只使用Unicode字符集的可打印子集。除NEL(\x85
)外,不允許使用C1控制塊中的字符(即字符\x80
-\x9F
)。
這幾乎是有效YAML:
d = 'tended (Journaled)"\n - " Support plug and play"\n'
你只需要在它前面一個"
和:
密鑰後:
d = '"tended (Journaled)":\n - " Support plug and play"\n'
(雖然我不知道,如果日誌式是正確的英文)
以下不是YAML:
d = '"tended (Journaled)":\n - "\x95 Support plug and play"\n'
因爲\x95
位於C1控制塊中。您必須手動替換這些字符,或放下它們。
沒有太多的ruamel.yaml
,可以幫助你轉換這樣的非法字符,但是可以使用Reader
的非法字符的正則表達式來掃描非法字符,並刪除它們:
from ruamel.yaml import YAML
from ruamel.yaml.reader import Reader
yaml = YAML(typ='safe')
def strip_invalid(s):
res = ''
for x in s:
if Reader.NON_PRINTABLE.match(x):
# res += '\\x{:x}'.format(ord(x))
continue
res += x
return res
d = '"tended (Journaled)":\n - "\x95 Support plug and play"\n'
print(yaml.load(strip_invalid(d)))
這給:
{'tended (Journaled)': [' Support plug and play']}
沒有任何進一步的手動干預。
如果取消對該行
# res += '\\x{:x}'.format(ord(x))
你作爲輸出:
{'tended (Journaled)': ['\x95 Support plug and play']}
Unicode代碼點十六進制95是Unicode字符的控制。請參閱https://en.wikipedia.org/wiki/Unicode_control_characters - 您想要顯示哪個字符? – Arminius
顯示字符串不是我的目標。我試圖將雜亂的數據清理成可分析的Python格式...在執行yaml.load()之前可以執行的任何命令或編碼以避免出現此錯誤消息? –