在CSS文件中查找类,然后使用python将其写入新文件

时间:2018-08-21 09:33:29

标签: python css string-parsing

我有一个.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)

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

2 个答案:

答案 0 :(得分:0)

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

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"
}

打印(匹配项)将打印:

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

答案 1 :(得分:0)

我最后解决了:

regex = r"(\.icon\w+.(.*?)\})"
classes = re.findall(regex, infile.read())

for entry in classes:
    outfile.write(entry[0] + '\n')