【问题标题】:Remove html formatting ">" from text file using Python csv.reader使用 Python csv.reader 从文本文件中删除 html 格式“>”
【发布时间】:2010-12-10 20:53:18
【问题描述】:

我有一个带有 ; 的文本文件用作分隔符。问题是它有一些 html 文本格式,例如 > 显然是 ;这会导致问题。 文本文件很大,我没有这些 html 字符串的列表,即有许多不同的示例,例如 $amp;。如何使用 python 删除所有这些。 该文件是姓名、地址、电话号码和更多字段的列表。我正在寻找 crap.html.remove(textfile) 模块

【问题讨论】:

标签: python html regex file csv


【解决方案1】:

看看来自here的代码:

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 添加了捕获。

【讨论】:

  • 我在 removehtml(text) 中收到错误 /Users/vmd/Dropbox/Marketing Material/Leads/formatleaddata.py 40 pass 41 return text # leave as is ---> 42 return re.sub ("?\w+;", fixup, text) /Library/Frameworks/Python.framework/Versions/5.1.0/lib/python2.5/re.pyc in sub(pattern, repl, string, count) 148如果是可调用的,则传递匹配对象并且必须返回 149 一个要使用的替换字符串。""" --> 150 return _compile(pattern, 0).sub(repl, string, count) 152 def subn(pattern, repl , 字符串, 计数=0):
  • 那是相当拗口,我不清楚错误是什么。你有异常类型吗?也许您应该尝试在单独的答案中发布您的异常详细信息,以便我们可以有正确的格式。
【解决方案2】:

最快的方法可能是在HTMLParser 中使用未记录但迄今为止稳定的unescape 方法:

import HTMLParser
s= HTMLParser.HTMLParser().unescape(s)

请注意,这必然会输出一个 Unicode 字符串,因此如果其中有任何非 ASCII 字节,则需要先s.decode(encoding)

【讨论】:

    【解决方案3】:

    在大多数 Unix 系统(包括 Mac OS X)上,您可以使用以下命令重新编码输入文本文件:

    recode html.. file_with_html.txt
    

    这取代了 >通过“>”等

    例如,您可以通过 Python 的 subprocess 模块调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多