Skip to main content
 首页 » 编程设计

python之去掉字符串中的\x## (Python)

2025年05月04日24zhujiabin

我需要从文件中提取描述,如下所示: “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\n多样化的生物和 NPC、新生物和 NPC、动态大小和统计缩放、增加生成,改进的人工智能,改进的派系等等。\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"

我已经想出了如何获得我需要的部分,但仍然有一些我不知道如何删除的不需要的数据: \xaf\x00Mart's Mutant Mod - RC4\n\n多样化的生物和 NPC、新生物和 NPC、动态大小和统计缩放、增加生成、改进 AI、改进派系等等。\n\n\x00

应该变成: Mart's Mutant Mod - RC4\n\n多样化的生物和 NPC、新生物和 NPC、动态大小和统计缩放、增加产卵、改进 AI、改进派系等等。\n\n\

基本上,我需要一种方法来摆脱\x## 东西(如果留在那儿,在 GUI 中显示时最终会变成奇怪的字符),但我还没有设法成功删除它们。

[如果您想知道,我正在处理的是 FO3 的 .esp 文件。]

请您参考如下方法:

你可以试试:

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 
>>>  

如您所见,这并不理想,但这至少是良好的开端。