[英]Remove html formatting “>” from text file using Python csv.reader
我有一个文本文件; 用作分隔符。 问题是它有一些html文本格式,例如>
显然是; 在这导致问题。 文本文件很大,我没有这些html字符串的列表,也就是有许多不同的例子,比如$amp;
。 如何使用python删除所有这些内容。 该文件是名称,地址,电话号码和一些其他字段的列表。 我正在寻找crap.html.remove(textfile)模块
最快的方法可能是在HTMLParser中使用未记录但迄今为止最稳定的unescape
方法:
import HTMLParser
s= HTMLParser.HTMLParser().unescape(s)
请注意,这必须输出Unicode字符串,因此如果您有任何非ASCII字节,则需要首先进行s.decode(encoding)
。
看看这里的代码:
import re, htmlentitydefs
##
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.
def unescape(text):
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except (ValueError, OverflowError):
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
当然,这只涉及HTML实体。 您可能在文本中有其他分号与CSV解析器混乱。 但我猜你已经知道......
更新 :为可能的OverflowError
添加了catch。
在大多数Unix系统(包括Mac OS X)上,您可以使用以下命令重新编码输入文本文件:
recode html.. file_with_html.txt
这取代了> 通过“>”等
例如,您可以通过Python的子进程模块调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.