【问题标题】:Getting rid of \x## in strings (Python)摆脱字符串中的 \x## (Python)
【发布时间】:2011-04-22 09:48:24
【问题描述】:

我需要从文件中提取描述,如下所示: “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,动态大小和统计缩放,增加生成,改进的 AI,改进的派系等等。\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 文件。]

【问题讨论】:

    标签: python string file


    【解决方案1】:

    如果你能做到这一点

    \xaf\x00Mart 的变种人模组 - RC4\n\n多样的生物和 NPC,新 生物和 NPC,动态大小和 统计缩放,增加产卵, 改进的人工智能,改进的派系,以及 更多。\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)
    

    【讨论】:

      【解决方案2】:

      我们要做的第一件事是pull up some docs。如果我们看一下底部,它会显示应该如何处理 SNAM 子记录。所以我们使用struct 来读取长度,然后我们从字符串中抓取那么多字节(我猜你忘记以二进制模式打开文件,因为在你的例子中计数是关闭的),以空终止。然后就没有什么可做的了,因为我们有我们想要的。

      【讨论】:

      • 又名 RTFM,LOL ;-) 当然,这假设你知道它在哪里以及你正在查看什么样的数据......
      【解决方案3】:

      你可以试试:

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

      如您所见,这并不理想,但这至少是一个不错的第一步。

      【讨论】:

        猜你喜欢
        • 2014-03-24
        • 2012-11-19
        • 1970-01-01
        • 2017-06-14
        • 2019-01-17
        • 2020-04-02
        • 2022-01-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多