所以我有 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 tofileinput.input()
or to theFileInput
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 asbackup='.<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
它回到同一个文件(fileinput
将print
输出重定向到文件)。进行就地文件编辑时,最好不要在其他任何地方打开 CSS 文件。 - 下一步是搜索
h1
每行的标签。我们使用re.match
来做到这一点.我不会详细解释如何使用正则表达式(您必须自己阅读)。我将只描述所使用的模式:
re.match(r"(.*)(h1\s*\{color:.*\})(.*)", line)
(.*) match and group everything before and after the
h1tag
\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/