【问题标题】:How do you replace specific characters in beautifulSoup?你如何替换beautifulSoup 中的特定字符?
【发布时间】:2015-02-14 15:07:31
【问题描述】:

我很清楚如何使用 bs4 替换标签中的文本,但是我如何将特定字符(例如 p-tag)实际更改为包含在 b-tag 中的另一个字符或字符串?

例如,如果我想加粗/突出显示段落中的所有 j。

【问题讨论】:

  • 这里不是替换单个字符,而是注入标签。这是不同的,因为文本元素必须分成三个,并且必须插入一个标签元素。

标签: python beautifulsoup


【解决方案1】:

如果要在文本中插入标签,则必须将整个文本分成 3 段;之前的所有内容,进入标签的文本,以及之后的所有内容。

每次在文本中找到匹配项时都必须执行此操作,因此您也需要在插入后跟踪结尾部分:

def inject_tag(text, start, end, tagname, **attrs):
    # find the document root
    root = text
    while root.parent:
        root = root.parent

    before = root.new_string(text[:start])
    new_tag = root.new_tag(tagname, **attrs)
    new_tag.string = text[start:end]
    after = root.new_string(text[end:])

    text.replace_with(before)
    before.insert_after(new_tag)
    new_tag.insert_after(after)
    return after

然后用上面的函数替换具体的索引:

>>> import re
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''\
... <p>The quick brown fox jumps over the lazy dog</p>
... ''')
>>> the = re.compile(r'the', flags=re.I)
>>> text = soup.p.string
>>> while True:
...     match = the.search(unicode(text))
...     if not match: break
...     start, stop = match.span()
...     text = inject_tag(text, start, stop, 'b')
... 
>>> print soup.prettify()
<html>
 <head>
 </head>
 <body>
  <p>
   <b>
    The
   </b>
   quick brown fox jumps over
   <b>
    the
   </b>
   lazy dog
  </p>
 </body>
</html>

【讨论】:

    【解决方案2】:

    您可以使用find_all() 函数获取所有&lt;p&gt; 元素,并通过常规表达式为您希望的字母注入&lt;b&gt; 元素,例如:

    from bs4 import BeautifulSoup
    import sys 
    import re
    
    soup = BeautifulSoup(open(sys.argv[1]))
    for p in soup.find_all('p'):
        p.string = re.sub(r'(r)', r'<b>\1</b>', p.string)
    
    print(soup.prettify(formatter=None))
    

    注意我使用formatter=None来避免HTML实体的转换。

    使用这个测试文本:

    <div>
        <div class="post-text" itemprop="text">
    
            <p>I'm well aware on how to replace texts in tags using bs4 but how would I actually change a specific character in, say a p-tag, into another character or string enclosed in a b-tag?</p>
    
    <p>An example would be if I wanted to bold/highlight all the j's in a paragraph.</p>
    
        </div>
    </div>
    

    像这样运行它:

    python script.py infile 
    

    产生:

    <html>
     <body>
      <div>
       <div class="post-text" itemprop="text">
        <p>
         I'm well awa<b>r</b>e on how to <b>r</b>eplace texts in tags using bs4 but how would I actually change a specific cha<b>r</b>acte<b>r</b> in, say a p-tag, into anothe<b>r</b> cha<b>r</b>acte<b>r</b> o<b>r</b> st<b>r</b>ing enclosed in a b-tag?
        </p>
        <p>
         An example would be if I wanted to bold/highlight all the j's in a pa<b>r</b>ag<b>r</b>aph.
        </p>
       </div>
      </div>
     </body>
    </html>
    

    【讨论】:

    • 这会插入 转义 尖括号。字符串内容现在是An example would be if I wanted to bold/highlight all the &amp;lt;b&amp;gt;j&amp;lt;/b&amp;gt;'s in a paragraph.
    猜你喜欢
    • 2014-02-18
    • 1970-01-01
    • 2021-05-26
    • 2021-08-23
    • 2016-11-20
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    相关资源
    最近更新 更多