2017-08-24 75 views
0

我面臨着「不可接受的字符#x0095:特殊字符不允許在」將YAML格式傳輸到Python字典對象時,「位置25」錯誤消息。
可能的解決方案是什麼?面對「不可接受的字符#x0095:特殊字符不允許在」<unicode string>「中,位置268」Python中的錯誤yaml.load

d = 'tended (Journaled)"\n - "\x95 Support plug and play"\n' 
a = yaml.load(d) 

要傳送的字符串刪節,不正確的YAML格式,但我想這是無關緊要在這種情況下。 我正在使用Python3

+0

Unicode代碼點十六進制95是Unicode字符的控制。請參閱https://en.wikipedia.org/wiki/Unicode_control_characters - 您想要顯示哪個字符? – Arminius

+0

顯示字符串不是我的目標。我試圖將雜亂的數據清理成可分析的Python格式...在執行yaml.load()之前可以執行的任何命令或編碼以避免出現此錯誤消息? –

回答

0

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']} 
+0

這將解決我的問題!非常感謝! –

0

您必須檢查無效字符的混亂數據。幸運的是,YAML讀者能產生必要的數據異常:

import yaml 

try: 
    d = 'tended (Journaled)"\n - "\x95 Support plug and play"\n' 
    a = yaml.load(d) 
except yaml.YAMLError as e: 
    print("Parsing YAML string failed") 
    print("Reason:", e.reason) 
    print("At position: {0} with encoding {1}".format(e.position, e.encoding)) 
    print("Invalid char code:", e.character) 

如果你運行這段代碼,它顯示正是你的性格\x95是罪魁禍首。現在,您必須更換/修復/詢問用戶,直到沒有發生異常。

+0

任何方法讓代碼運行,但離開\ x95的方式? –