重疊的HTML標籤多串本身不覺得自己是一個清晰的問題標題,所以我會提供,而不是一個例子:合併具有相同的內容,但在Python
我有一個例子字符串:
Created and managed websites for clients to communicate securely
,它有很多「版本」。這意味着字符串的「版本」中的詞或短語將被包含在HTML div標籤中,即<div style="font-size: 0.1000000">foo bar</div>
。 (這些標記是任意的,考慮到字體大小屬性的數字對應於稍後將被用作其它CSS特性,現在是不相關的分數。)這裏有4個版本的字符串:
Created and <div style="font-size: 1">managed</div> websites for clients to communicate securely
Created and <div style="font-size: 2">managed websites</div> for clients to communicate securely
Created and managed websites for clients to <div style="font-size: 3">communicate</div> securely
<div style="font-size: 4">Created</div> and managed websites for clients to communicate securely
我想所有這些版本合併到這一點:
<div style="font-size: 4">Created</div> and <div style="font-size: 2"><div style="font-size: 1">managed</div> websites</div> for clients to <div style="font-size: 3">communicate</div> securely
我們在這裏看到,有(有font-size: 2
和font-size: 1
在標籤重疊)標籤。字符串版本的數量可以在1到50之間的任何地方,因此可能有多個重疊。
這裏是我到目前爲止使用正則表達式:
import re
div_str = "<div style=.*</div>" # the div tags
div_text_str = "(?<=(>)).*(?=(</div>))" # the content inside the div tags
# compile the regexes
div_regex = re.compile(div_str)
div_text_regex = re.compile(div_text_str)
def merge_strings(str1, str2):
# grab the div tag off the first version
div = div_regex.search(str1).group()
# grab the contents of that div tag
div_text = div_text_regex.search(div).group()
# find the div content in the second version, then substitute
# with the div tag
return re.sub(div_text, div, str2)
我運行在一個循環此功能,並試圖在同一時間合併兩個字符串,直到我得到的最終輸出。我面臨的問題是,重疊標籤不適用於此函數,因爲正則表達式模式不匹配它。此外,一次替換多個div標籤失敗。
任何幫助,將不勝感激!
BeautifulSoup正在項目中用於解析輸入的HTML!您從這些行中提取的文本已經存在 - 它們正在用於返回這些不同版本的不同分析中。最終,該項目解析一個HTML文件 - >做分析,生成這些版本 - >替換原來的HTML內容與所有這些版本合併在我的例子中。 – kug3lblitz