代码之家  ›  专栏  ›  技术社区  ›  Lounges

在python中解码html编码字符串

  •  1
  • Lounges  · 技术社区  · 15 年前

    我有以下字符串。。。

    "Scam, hoax, or the real deal, he’s gonna work his way to the bottom of the sordid tale, and hopefully end up with an arcade game in the process."
    

    我需要把它变成这根绳子。。。

    骗局,骗局,或是真正的交易, 他会努力工作到最后 肮脏故事的最底层,以及 希望以一个街机游戏结束 在这个过程中。

    这是相当标准的HTML编码,我一辈子都不知道如何在python中转换它。

    我发现: GitHub

    它非常接近于工作,但是它不输出撇号,而是输出一些非unicode字符。

    下面是GitHub脚本的输出示例。。。

    他会一路走到底的 肮脏的故事,并希望结束 在这个过程中有一个街机游戏。

    1 回复  |  直到 15 年前
        1
  •  4
  •   Community CDub    7 年前

    您试图做的是所谓的“HTML实体解码”,它包含在许多过去的堆栈溢出问题中,例如:

    下面是使用 Beautiful Soup 用于解码示例的HTML解析库:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    from BeautifulSoup import BeautifulSoup
    
    string = "Scam, hoax, or the real deal, he’s gonna work his way to the bottom of the sordid tale, and hopefully end up with an arcade game in the process."
    s = BeautifulSoup(string,convertEntities=BeautifulSoup.HTML_ENTITIES).contents[0]
    print s
    

    骗局、恶作剧或真正的交易,他 他会一路走到底的 肮脏的故事,并希望结束 在这个过程中有一个街机游戏。