在 css 文件中找到 类 并用 python 将它们写入新文件
Find classes in css file and write them in a new file with python
我有一个 .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)
myfile.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}']
最后我解决了:
regex = r"(\.icon\w+.(.*?)\})"
classes = re.findall(regex, infile.read())
for entry in classes:
outfile.write(entry[0] + '\n')
我有一个 .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)
myfile.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}']
最后我解决了:
regex = r"(\.icon\w+.(.*?)\})"
classes = re.findall(regex, infile.read())
for entry in classes:
outfile.write(entry[0] + '\n')