我覺得這是一個奇怪的請求。 我從一個字符串開始,然後通過一個處理字符串(很多行)的函數來運行它,並返回一個列表。 此列表包含時間戳和文本。這是一個LRC文件,實際上(歌詞跟蹤時間)將字符串轉換爲列表並返回
我正在寫一些kodi(xmbc)模塊,並且它運行它自己的python解釋器。我可以在插件之間共享數據,但只能作爲字符串共享。 (將它們設置爲kodi中的一個屬性)
所以,我有一個列表,我可以用str()方便地將其轉換爲字符串,但是我無法將它恢復到我可以處理的同一個列表中。
一些示例文本:
[01:45.17]<i>I cant remember anything
[01:48.80]Cant tell if this is true or dream
[01:52.29]Deep down inside I feel to scream
[01:55.91]This terrible silence stops me
這回來從我的解析器功能列表。在原始形式是這樣的:
[{'timestamp': dbus.Int64(105170L), 'id': dbus.UInt32(0L), 'text': 'I cant remember anything'}, {'timestamp': dbus.Int64(108800L), 'id': dbus.UInt32(1L), 'text': 'Cant tell if this is true or dream'}, {'timestamp': dbus.Int64(112290L), 'id': dbus.UInt32(2L), 'text': 'Deep down inside I feel to scream'}, {'timestamp': dbus.Int64(115910L), 'id': dbus.UInt32(3L), 'text': 'This terrible silence stops me'}]
有一次,我將它轉換爲一個字符串STR(),它看起來酷似上面有什麼作爲字符串。
現在,我想要將此字符串恢復爲原始列表形式。所以,我可以通過工藝生產線,做它行,並引用的元素,因爲我可以用轉換的預表:
print line['text']
print line['timestamp']
我已經試過各種事情,但似乎無法把它找回來列入我可以循環的列表中。
我看着json.dumps( '行' 是列表):
lines_str=json.dumps(lines)
newlines=json.dumps(lines_str)
print newlines.__class__.__name__
但是這告訴我,行依然是 「STR」 於是,我試着用EVAL:
lines_str=str(lines)
newlines=eval(lines_str)
但eval不喜歡字符串格式:
Traceback (most recent call last):
File "./l.py", line 33, in <module>
newlines=eval(lines_str)
File "<string>", line 1, in <module>
然後我試了literal_eval從ast模塊:
lines_str=str(lines)
newlines=ast.literal_eval(lines_str)
但是,喜歡我的字符串甚至更少。
File "/usr/lib/python2.7/ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string
我可以在一個插件中執行此任務而不是其他插件。但是本着設計的精神,我有一個完成這項工作的後端,以及繪製漂亮照片的前端。我寧願將工作保留在後端,並儘量減少在前端部分加載模塊和進程。
你爲什麼'json.dumps'ing兩次? –
因爲顯然通過我所有的測試,我忘了把它改成json.loads,它可以工作。那個怎麼樣。 – jgauthier
請[編輯]你的問題,並確切地顯示最初在'線路'中的內容。 – martineau