我正在尝试解析一些具有令人讨厌的内联样式的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;
或其他随机数。
我尝试了漂亮的汤,我想出了如何去除整个标签,这不是我想要的。我不知道如何使用正则表达式。而且我读到最好避免尝试使用正则表达式编辑HTML。
我的主意是使用漂亮的汤将所有span标签保存到一个变量中,然后使用string.find()
来获取单词间距中所有“ w”的索引,然后找到下一个半栏。然后,在获得列表之后,找到一种方法来在这些索引处剪切字符串并将剩余部分重新组合在一起。也许在“;”处分裂更好...目前我不知道了。大脑是油炸和疲倦的。 :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--; 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%;
答案 0 :(得分:0)
我猜测也许您可能想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%;"
如果您想探索/简化/修改表达式,可以 在右上角的面板上进行了说明 regex101.com。如果您愿意, 也可以在this link中观看它的匹配方式 针对一些样本输入。
答案 1 :(得分:0)
您可以匹配具有该属性的元素并删除该部分。
我在memoryCacheMock
.Setup(x => x.CreateEntry(It.IsAny<object>()))
.Returns(Mock.Of<ICacheEntry>);
上分割了样式属性(仅用于相关标签),然后重新组合以排除不想要的对
;
但是您可以轻松地更新';'.join([i for i in t['style'].split(';') if 'word-spacing' not in i])
word-spacing
阅读: