2010-10-07 80 views
1

我需要從文件中提取描述,如下所示: 「TES4!\ x01 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ X00 \ X00 \ X00 \ X00 \ X00 \ X00 \ X00 \ X0F \ X00 \ X00 \ x00HEDR \ X0C \ X00 \ XD7 \ xa3p 2 H \ X03 \ X00 \ X00 \ X00 \ X08 \ X00 \ xffCNAM \噸\ x00Martigen \ x00SNAM \ xaf \ x00Mart's Mutant Mod - RC4 \ n \ nDiverse生物& NPC,新生物& NPC,動態大小和統計縮放,增加的生成物,改進的AI,改進的派系等等。\ n \ n \ x00MAST \ r \ x00Fallout3.esm \ x00DATA \ X08 \ X00 \ X00 \ X00 \ X00 \ X00 \ X00 \ X00 \ X00 \ x00MAST \ X16 \ x00Mart的突變Mod.esm \ x00DATA \ X08"擺脫字符串中的 x ##(Python)

我laready想出如何獲得我需要的部分,但仍然存在一些不需要的數據,我不知道如何擺脫作者: \ xaf \ x00Mart's Mutant Mod - RC4 \ n \ nDiverse生物& NPC,新生物& NPC,動態大小和統計縮放,增加的生成物,改進的AI,改進的派系等等。\ n \ n \ x00

應該變成: 沃爾瑪的突變國防部 - RC4 \ n \ nDiverse生物&的NPC,新的生物&的NPC,提供動態的大小和統計比例,增加產卵,提高AI,改善派別,以及更多\ n \ n \

基本上,我需要一種方法來擺脫\ x ##的東西(如果留在那裏最終會在GUI中顯示爲怪異字符),但我沒有設法成功地刪除他們。

[在你不知道的情況下,它是FO3 .esp文件我用瞎搞]

回答

4

你可以嘗試:

import string 

cleaneddata = ''.join(c for c in data if c in string.printable) 

這是假設你已經data一個字符串。

下面是它的工作對我來說:

>>> s = """TES4!\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\x00\x00\x00HEDR\x0c\x00\xd7\xa3p?h\x03\x00\x00\x00\x08\x00\xffCNAM\t\x00Martigen\x00SNAM\xaf\x00Mart's Mutant Mod - RC4\n\nDiverse creatures & NPCs, new creatures & NPCs, dynamic size and stat scaling, increased spawns, improved AI, improved factions, and much more.\n\n\x00MAST\r\x00Fallout3.esm\x00DATA\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00MAST\x16\x00Mart's Mutant Mod.esm\x00DATA\x08""" 
>>> print ''.join(c for c in s if c in string.printable)TES4!HEDR 
     p?hCNAM MartigenSNAMMart's Mutant Mod - RC4 

Diverse creatures & NPCs, new creatures & NPCs, dynamic size and stat scaling, increased spawns, improved AI, improved factions, and much more. 

Fallout3.esmDATAMASTMart's Mutant Mod.esmDATA 
>>> 

並不理想,因爲你可以看到,但可能至少是一個良好的開端。

+0

+1讓你的6666的評價並不像撒旦:-) – gtrak 2010-10-07 15:03:50

4

我們做的第一件事是pull up some docs。如果我們看一下底部,它會顯示如何處理SNAM子記錄。所以我們使用struct來讀取長度,然後我們從字符串中獲取很多字節(我猜你忘了以二進制模式打開文件,因爲計數在你的例子中是關閉的),以null結束。然後沒有什麼可以做的了,因爲我們有我們的目標。

+0

又名RTFM,LOL ;-)當然是假定你知道它在哪裏,你在看什麼樣的數據的... – martineau 2010-10-07 18:29:28

+0

+1。比我的回答更好。 – aaronasterling 2010-10-07 22:45:36

0

如果你是高達

點\ XAF \ x00Mart的突變國防部 - RC4 \ n \ nDiverse生物&的NPC,新 生物&的NPC,提供動態的大小和 統計比例,增加產卵, 改進AI,改善派別和 更\ n \ n \ x00的

,你可以做以下做擺脫過去的不必要\ X ##的:

exp = re.compile(r"\\x[\w]") 
newStr = [s for s in str.split("\\x00") if not re.search(exp, s)] 
newStr = "".join(newStr)