首页 > 解决方案 > 如何从 HTML 文件中删除 Python 中的 HTML 标记?

问题描述

摘要:我将使用什么正则表达式字符串来删除 HTML 文档中的标签?虽然,这可能与之前的答案重复:How to remove only html tags in a string? 删除 String 中的 HTML 标签,我还不能完全用这些语言编程,所以这就是我问这个问题的原因。

我正在完成 Google 的 Python 练习:https ://developers.google.com/edu/python/exercises/baby-names 它需要你使用正则表达式解析 HTML 数据(HTML 是结构化的,因此更容易)。我在删除数据周围的标签时遇到问题:

   def extract_names(filename):
  """
  Given a file name for baby.html, returns a list starting with the year string
  followed by the name-rank strings in alphabetical order.
  ['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...]
  """
  # +++your code here+++
  #open and read file
  file = open(filename,'r')
  HTML = file.read()
  #html file
  #print(HTML)

  #extract date
  date = re.search(r'(Popularity in )([\d]+)',HTML)
  print('Date: ',date.group(2))

  #find rank and name remove html tags
  ranking_tags = re.findall(r'<td>[\d]</td>',HTML)
  rankings = []
  name_tags = re.findall(r'<td>[a-z]</td>',HTML,re.IGNORECASE)
  names = []

  for value in ranking_tags:
      rankings.append(re.sub('[<td></td>]','',value))

  for value in name_tags:
    names.append(re.sub('[<td></td>]','',value))
  print(rankings)
  print(names)

目前,我的正则表达式不会替换标签,因为它们是错误的。我已经尝试自学如何删除标签无济于事: http: //www.cbs.dtu.dk/courses/27610/regular-expressions-cheat-sheet-v2.pdfhttps://www.tutorialspoint .com/python/python_reg_expressions.htm 以及在写这篇文章之前看看其他景点。

任何建议将不胜感激。

标签: pythonhtmlregexpython-3.xpython-3.4

解决方案


如果regex不需要并完成工作,您可以检查现有的实现。

姜戈的strip_tags

https://github.com/django/django/blob/master/django/utils/html.py#L183

def _strip_once(value):
    """
    Internal tag stripping utility used by strip_tags.
    """
    s = MLStripper()
    s.feed(value)
    s.close()
    return s.get_data()


@keep_lazy_text
def strip_tags(value):
    """Return the given HTML with all tags stripped."""
    # Note: in typical case this loop executes _strip_once once. Loop condition
    # is redundant, but helps to reduce number of executions of _strip_once.
    value = str(value)
    while '<' in value and '>' in value:
        new_value = _strip_once(value)
        if len(new_value) >= len(value):
            # _strip_once was not able to detect more tags
            break
        value = new_value
    return value

您可以修改该实现。

Python 标准库及其xml模块

https://docs.python.org/3/library/xml.etree.elementtree.html

它包含有关如何正确使用它的示例。

使用lxml

https://lxml.de/api/lxml.etree-module.html#strip_tags

示例用法:

strip_tags(some_element,
    'simpletagname',             # non-namespaced tag
    '{http://some/ns}tagname',   # namespaced tag
    '{http://some/other/ns}*'    # any tag from a namespace
    Comment                      # comments (including their text!)
    )

推荐阅读