python - 如何使用 python 从内联样式标记中删除特定值对?

标签 python regex string parsing beautifulsoup

我正在尝试解析一些具有令人讨厌的内联样式的 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/

相关文章:

python - 如何使用python在打印语句的for循环中插入换行符

javascript - 需要相同重复符号的信用卡正则表达式

正则表达式:用制表符替换 4 个空格组(从换行符到一个字符)

python - 使用 python 打印图案的替代解决方案

c# - 如何在 C# 中将 "=?utf-8?B?...?="解码为字符串

java - 如何在 sql 语句(Java)中使用大写的列名和表名?

python - 真正的程序员如何做服务器循环?

python - SQLAlchemy:合并重复标签的有效方法

python - 使用 Pandas 绘制包含列表的列

c# - 正则表达式模式与某些节目标题不匹配