我正在尝试解析一些具有令人讨厌的内联样式的 html。 它看起来像这样
<span class="text_line" data-complex="0" data-endposition="4:2:86:5:0" data-position="4:2:74:2:0" style="font-family: scala-sans-offc-pro--; width: 100%; word-spacing: -2.66667px; font-size: 24px !important; line-height: 40px; font-variant-ligatures: common-ligatures; display: block; height: 40px; margin-left: 75px; margin-right: 155px;">
我试图仅删除属性值对word-spacing: -2.66667px;
。问题是这样的行有几百条,没有两条是相同的。有时间距是 word-spacing: -4px
,有时是 word-spacing: -3.78632px;
或其他随机数。
我尝试了 BeautifulSoup ,我想出了如何删除整个标签,这不是我想要的。我不知道如何用正则表达式来做到这一点。我读到最好避免尝试使用正则表达式编辑 HTML。
我的想法是正确的,即使用 beautiful soup 将所有 span 标签保存到一个变量中,然后使用 string.find() 来获取字间距中所有“w”的索引,然后找到下一个半列。然后,在我有了一个列表后,找到一种方法来剪切这些索引处的字符串并将剩余部分重新连接在一起。也许在“;”处 split 更好...我现在不知道更多了。脑子又炸又累。 :P
def __init__(self, first_index, last_index):
self.first = first_index
self.last = last_index
def getIndices(text, start_index):
index = CutPointIndex(None, None)
index.first = text.find("word-spacing", start_index, end_index)
if(index.first != -1):
index.last = text.find(";", index.first , end_index)
return index
鉴于类似
style="font-family: scala-sans-offc-pro--; 宽度: 100%; 字间距: -3.71429px;"
或style="font-family: scala-sans-offc-pro--;宽度:100%;字间距:-5px;
或任何其他值的变化,预期结果应该是
style="font-family: scala-sans-offc-pro--; 宽度: 100%;
最佳答案
我猜您可能想要re.sub
变量word-spacing
:
import re
regex = r"\s*word-spacing\s*:\s*[^;]*;"
test_str = '''
style="font-family: scala-sans-offc-pro--; width: 100%; word-spacing: -3.71429px;"
style="font-family: scala-sans-offc-pro--; width: 100%; word-spacing: -5px;"
style="font-family: scala-sans-offc-pro--; width: 100%;"
'''
print(re.sub(regex, "", test_str))
<小时/>
输出
style="font-family: scala-sans-offc-pro--; width: 100%;"
style="font-family: scala-sans-offc-pro--; width: 100%;"
style="font-family: scala-sans-offc-pro--; width: 100%;"
<小时/>
<小时/>If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
关于python - 如何使用 python 从内联样式标记中删除特定值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57703742/