CSS 属性的 Python 文件内容替换

标签 python html css python-3.x

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

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

配置文件:

color: #ffffff;

CSS 文件:

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

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

最佳答案

您可以使用 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 block 是我们读取配置文件以获取 color: #ffffff; 的地方值(value)。我在这里假设它位于自己的行中(这就是我使用 startswith 的原因)。我不知道你的配置文件是什么样的,所以根据你的需要调整它。
  • 然后,我们存储color: #ffffff;进入color_config , 格式为 h1 { .. }字符串。我们现在对其进行格式化,以便以后轻松搜索和替换。
  • 第二个with block 执行就地文件搜索和替换。它使用 fileinput.input inplace参数设置为 True .来自文档:

Optional in-place filtering: if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup='.<some extension>'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed.

  • 在这一秒with block ,我们读取 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 }

  • 如代码注释中所述,我们可以得到 h1使用 match.group 标记.
  • 最后一步是做实际的 string replacement使用 color_config早点阅读,然后将其打印到文件中。请注意,我有选择地传递了一个 end=""print ,因为默认情况下 print输出包括换行符。同样,我不知道您的 CSS 文件是什么样的,因此请根据需要进行调整。

关于CSS 属性的 Python 文件内容替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50065151/

相关文章:

python - 读取 .sql 文件以在 Python 中执行 (pymysql)

python - Django - 一次测试多个 View

python - Mac 上 Python 的全局库的位置?

javascript - 如何获得一个函数来检查属性是否被禁用?

html - 工具提示被 div 容器截断

CSS:x 轴上的固定位置而不是 y 轴?

css - 选择框的 css 属性不是从其父级继承的。

javascript - 在 Python 中使用 Javascript 变量

jquery - 插入一个类到一个div和一行html

javascript - 在运行时 HTML 元素上调用单击事件处理程序