gpt4 book ai didi

python - 在 css 文件中查找类并用 python 将它们写入新文件中

转载 作者:行者123 更新时间:2023-11-28 01:14:16 26 4
gpt4 key购买 nike

我有一个 .css 文件,没有缩进,有一些类定义。我需要提取所有以 .icon 开头的类,例如:

.icon_arrow:before {
content="/256"
}

并将它们写入一个新文件中。我尝试读取所有行并在 .icon 之间写入字符串,如下所示:

infile = open('myfile.css', 'r')
outfile = open('newfile.css', 'w')
copy = False

with infile as css:
for line in css:
if line.strip() == ".icon":
copy = True
elif line.strip() == '}':
copy = False
elif copy:
outfile.write(line)

但是我得到一个空文件。有什么建议吗?

最佳答案

我认为这可以解决您的问题:

import re

textfile = open('myfile.css', 'r')
filetext = textfile.read()

matches = re.findall("^\.icon.*\n+.*\n+}", filetext, re.MULTILINE)

print(matches)

outfile = open('newfile.css', 'w')

for match in matches:
outfile.write(match)

我的文件.css

.icon_arrow:before {
content="/111"
}

.icon_arrow:before {
content="/222"
}

.icon_arrow:before {
content="/333"
}

.somethingelse:before {
content="/444"
}

.somethingelse:before {
content="/555"
}

print(matches) 将打印:

['.icon_arrow:before {\n    content="/111"\n}', '.icon_arrow:before {\n    content="/222"\n}', '.icon_arrow:before {\n    content="/333"\n}']

关于python - 在 css 文件中查找类并用 python 将它们写入新文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51945708/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com