python - 如何从 JSON 文件中去除所有 HTML 内容?

标签 python html regex json data-cleaning

我想通过丢弃包含在 HTML 标签中的所有文本(包括标签本身)来清除错误提取的 HTML 内容的 JSON 文件。

我试过这个功能:

def stripIt(s):
    txt = re.sub('</?[^<]+?>.*?</[^<]+?>', '', s)
    return re.sub('\s+', ' ', txt)

但是当我将它应用到 JSON 文件时,它可能会破坏 JSON 文件,给出一些错误。

HTML 内容也因缺少标签、仅关闭标签等而损坏。

那么如何在不破坏文件的情况下从 JSON 文件中剥离所有 HTML 内容呢?

最佳答案

How do I strip the html content out from a json file without breaking it?

与任何其他序列化数据结构的方式相同。通过使用适当的解析器(在这种情况下,是一个小的递归函数)。

import json
import re

json_string = """{
  "prop_1": {
    "prop_1_1": ["some <html> data", 17, "more <html> data"],
    "prop_1_2": "here some <html>, too"
  },
  "prop_2": "and more <html>"
}"""

def unhtml(string):
    # replace <tag>...</tag>, possibly more than once
    done = False
    while not done:
        temp = re.sub(r'<([^/]\S*)[^>]*>[\s\S]*?</\1>', '', string)
        done = temp == string
        string = temp
    # replace remaining standalone tags, if any
    string = re.sub(r'<[^>]*>', '', string)
    string = re.sub(r'\s{2,}', ' ', string)
    return string.strip()

def cleanup(element):
    if isinstance(element, list):
        for i, item in enumerate(element):
            element[i] = cleanup(item)
    elif isinstance(element, dict):
        for key in element.keys():
            element[key] = cleanup(element[key])
    elif isinstance(element, basestring):
        element = unhtml(element)

    return element

用作

data = json.loads(json_string)
cleanup(data)
json_string = json.dumps(data)
print json_string

丢弃 HTML 标签的正则表达式只解决了一半的问题。所有字符实体(如 &< 将保留在字符串中。

重写 unhtml() 以使用 proper parser ,也是。

关于python - 如何从 JSON 文件中去除所有 HTML 内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27800551/

相关文章:

python - 在 Python 2.7 中创建任意大小数组的最简单方法

python - 在不打开 Excel 工作表的情况下计算它们(openpyxl 或 xlwt)

javascript - 为日期/时间输入字段设置默认 View ,覆盖用户区域设置?

javascript - jQuery 选择器多选菜单/正则表达式

regex - Jenkins Groovy 控制台日志上的构建后插件多行正则表达式

android - 使用谷歌云消息时项目未列入白名单 - 适用于 Android 的 GCM 服务

python - 保存边框图像

javascript - 如何从 Canvas 上的多个旋转弧中删除直线?

javascript - 使用 JavaScript(或 jQuery)确定 map (imageMap)中的哪个区域被点击

C# - 文件路径的正则表达式,例如C :\test\test. 可执行文件