如何从HTML文件中删除Python中的HTML标签?

时间:2018-10-25 16:25:12

标签: python html regex python-3.x python-3.4

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

我正在完成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 以及在撰写本文之前先看其他景点。

任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

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

Django的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!)
    )