【问题标题】:Using beautiful soup regex in a large HTML file python在大型 HTML 文件 python 中使用漂亮的汤正则表达式
【发布时间】:2019-03-14 14:10:16
【问题描述】:

我无法在任何地方找到这个特定问题的答案,而且我自己也无法弄清楚。

我有一个大的 HTML 文件,它是电子邮件的模板。我已将其作为文本文件读入并将值保存在变量 html_string 中我有几行包含语句,例如

<span style="color: #ff0000;"> {column_1}</span>

<span style="color: #ff0000;">{column_2}</span>

其中 {column_*} 部分将替换为其他值,例如名称。另一个问题建议使用诸如

之类的东西
    soup = BeautifulSoup(html_string, features="html5lib")

    target = soup.find_all(text=re.compile('^{column_$'))

    print("Target:")
    print(target)

    for v in target:
        # do something (this never gets accessed due to empty list)

返回

   >>Target:
   >> []

而我希望它会返回 {column_*} 的位置列表或其他我可以用来插入我自己的字符串的东西。

我为 re.compile(x) 部分尝试了几种不同的结构,但没有任何效果。

任何帮助将不胜感激!

编辑------ 出于某种原因,即使我导入了 bs4,也只有 findAll 函数会执行我需要的功能 - 通常建议不要使用它,因为 bs4 中的 find_all 会“做同样的事情” ¬(..)¬

    soup = BeautifulSoup(html_string, features="html5lib")
    target = soup.findAll(text=re.compile('{column_.}'))

    for v in target:
        v.replace_with(dictionary[str(v)])

    body = str(soup)

【问题讨论】:

    标签: python html regex


    【解决方案1】:

    您可以使用正则表达式来查找模板并将文本替换为所需的值:

    import re
    vals = {'column_1':'Name', 'column_2':'Age'}
    result = re.sub('\{.*?\}', lambda x:vals[x.group()[1:-1]], content)
    print(result)
    

    输出:

    <span style="color: #ff0000;"> Name</span>
    
    <span style="color: #ff0000;">Age</span>
    

    【讨论】:

      【解决方案2】:

      你也可以使用字典吗?

      html  = '''
      <span style="color: #ff0000;">column_1</span>
      <span style="color: #ff0000;">column_2</span>
      '''
      soup = bs(html, 'lxml')
      dict = {'column_1':'Name', 'column_2':'Age'}
      
      for item in soup.select('[style="color: #ff0000;"]'):
          try:
              item.string = dict[item.text]
          except:
              continue
      print(soup)
      

      【讨论】:

        猜你喜欢
        • 2012-10-12
        • 2017-06-05
        • 2017-04-27
        • 2020-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-24
        • 1970-01-01
        相关资源
        最近更新 更多