我想通过丢弃包含在 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/