【问题标题】:Python file content replacement for CSS propertiesCSS 属性的 Python 文件内容替换
【发布时间】:2018-04-28 08:19:26
【问题描述】:

所以我有 2 个文件:config.txt 和一个 CSS 文件。

我要做的是从配置文件中读取颜色属性并将其替换到 CSS 文件中。

配置文件:

color: #ffffff;

CSS 文件:

body{ color: #000000;} h1{color:#000000;}

我需要做的是将CSS文件color替换为配置文件color,如何使用Python文件操作仅替换h1标签的color而不是@987654328 @标签?

【问题讨论】:

    标签: python html css python-3.x


    【解决方案1】:

    您可以结合使用 fileinput 模块进行就地文件编辑,使用 re 正则表达式模块对特定的 h1 标记进行搜索和替换。

    这是代码:
    (请注意,我使用“config.txt”作为配置文件,使用“output.css”作为 CSS 文件)

    # read the color from the config file
    color_config = ""
    with open("config.txt", "r") as config_file:
        for line in config_file:
            if line.startswith("color"):
                color_config = "h1 {" + line.strip() + "}"
                break
    
    # update the css file in-place
    with fileinput.input(files=("output.css"), inplace=True) as css_file:
        for line in css_file:
            # the h1 tag could be on its own line or could be part of
            # a line with other styles, so we capture them in groups
            matches = re.match(r"(.*)(h1\s*\{color:.*\})(.*)", line)
            if matches:
                # group(0): entire matching line
                # group(1): everything before the h1 tag
                # group(2): the h1 tag
                # group(3): everything after the h1 tag
                print(line.replace(matches.group(2), color_config), end="")
            else:
                print(line, end="")
    

    一些解释:

    • 第一个with 块是我们读取配置文件以获取color: #ffffff; 值的地方。我在这里假设它放在自己的行上(这就是我使用startswith 的原因)。我不知道您的配置文件是什么样的,所以只需根据您的需要进行调整。
    • 然后,我们将color: #ffffff; 存储到color_config 中,格式为h1 { .. } 字符串。我们现在对其进行格式化,以便以后搜索和替换。
    • 第二个with 块执行就地文件搜索和替换。它使用fileinput.input 并将inplace 参数设置为True。来自文档:

    可选的就地过滤:如果关键字参数inplace=True 是 传递给fileinput.input()FileInput 构造函数,文件 移动到备份文件,标准输出被定向到输入 文件(如果已存在与备份文件同名的文件,则 将被静默替换)。这使得编写过滤器成为可能 重写其输入文件。如果 backup 参数是 给定(通常为backup='.<some extension>'),它指定 备份文件的扩展名,并且备份文件仍然存在;经过 默认为'.bak',输出时删除 文件已关闭。

    • 在第二个with 块中,我们读取CSS 文件的每一行,替换部分字符串,然后print 将其返回到同一个文件(fileinputprint 输出重定向到文件) .在进行就地文件编辑时,最好不要在其他任何地方打开 CSS 文件。
    • 下一步是从每一行中搜索h1 标记。我们使用re.match 来执行此操作。我不会详细说明如何使用正则表达式(您必须自己阅读)。我将只描述使用的模式:

    re.match(r"(.*)(h1\s*\{color:.*\})(.*)", line)

    (.*) match and group everything before and after theh1tag
    \s* match 0 or more spaces between h1 and {
    \{, \} match the brackets (escaped, because {} are regex special chars)
    color:.* match any number of characters between color: and }

    • 如代码 cmets 中所述,我们可以使用 match.group 获取 h1 标签。
    • 最后一步是使用之前读取的color_config 执行实际的string replacement,然后将其打印到文件中。请注意,我可以选择将end="" 传递给print,因为默认情况下print 输出包含换行符。同样,我不知道您的 CSS 文件是什么样的,因此请根据需要进行调整。

    【讨论】:

    • 感谢您的详细回答@Gino Mempin!您认为我可以将这种方法用于 SASS 文件吗?如果 css 文件是这样格式化的呢? h1{ 颜色:#000000;字体系列:'Verdana',无衬线;字体大小:18px; }(在列中,因为它不会在评论框中显示为列:)
    • 更清楚地说,当我得到一个更复杂的 CSS 文件时,我只想替换“颜色:xxxxxx;”部分而不是整个 h1 标签。我怎样才能做到这一点?
    • @Maia 根据您的 CSS/SASS 文件/格式,您不需要捕获整个 h1 标记,只需捕获带有 color 的行,例如“color:.*; . 我建议你阅读一下How to Use Regex。这是一个非常有用的技能。
    • @Maia 由于您将逐行解析文件,因此您可以(1)首先查找具有特定开始标签的行(例如“h1 {”)然后应用正则表达式匹配并替换到结束的“}”标签,或者(2)您可以首先收集{..}之间的所有多行,应用正则表达式匹配,然后一次性替换块。
    猜你喜欢
    • 2012-10-15
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-18
    • 1970-01-01
    相关资源
    最近更新 更多