我知道,这似乎是一个简单的问题,但请阅读我的问题。
我想提取符合以下模式的html类名:
regex = re.compile(r'([\w-]+)-([#\w\d,%()\.]+)')
并将其作为CSS样式写入不同的文件中。
为此,我有一个我们将要使用的值和属性的字典:
keyword = {
'c':'color',
'bg':'background',
'red':'#ed1a1a',
'blue':'#60a8ff'
#etc
}
例:
html文件:<div class="c-red bg-blue"> content </div>
css文件中的输出:
.c-red{
color: red;
}
.bg-blue{
background: blue;
}
这是基本上我的脚本:
regex = re.compile(r'([\w-]+)-([#\w\d,%()\.]+)')
with open('index.html', 'r') as file:
with open('style.css', 'a+') as newfile:
lines = file.readlines()
for line in lines:
if 'class="' in line:
to_replace = regex.findall(line)
for key in to_replace:
prop=key[0]
value=key[1]
name='.'+prop+'-'+value
if prop and value in keyword:
var1 =('\n'+name+'{'+
'\n'+keyword[prop]+': '+
keyword[value]+';'+
'\n'+'}')
newfile.write(var1)
但如果我有多个类似的HTML字符串,例如:
<div class="c-red bg-blue"> content </div>
<div class="c-red bg-blue"> content2 </div>
<div class="c-red bg-blue"> content2 </div>
该脚本将编写CSS命令的次数与HTML文件中的字符串一样多。
我该如何防止这种重复?
我试过了:
var1=''
和
if var1 in newfile:
break
else:
newfile.write(var1)
但这些都没有奏效。
在您写入之前添加附加到集合。然后在写作之前简单地检查一下。这不会检查以前写入新文件的项目
written = set()
regex = re.compile(r'([\w-]+)-([#\w\d,%()\.]+)')
with open('index.html', 'r') as file:
with open('style.css', 'a+') as newfile:
lines = file.readlines()
for line in lines:
if 'class="' in line:
to_replace = regex.findall(line)
for key in to_replace:
prop=key[0]
value=key[1]
name='.'+prop+'-'+value
if prop and value in keyword:
var1 =('\n'+name+'{'+
'\n'+keyword[prop]+': '+
keyword[value]+';'+
'\n'+'}')
if var1 not in written: #check if you already wrote it
newfile.write(var1) # if not write it
written.add(var1) # you wrote it so add it the list of things you check against
我编辑了你的代码:
import re
keyword = {
'c':'color',
'bg':'background',
'red':'#ed1a1a',
'blue':'#60a8ff'
#etc
}
regex = re.compile(r'([\w-]+)-([#\w\d,%()\.]+)')
with open('index.html', 'r') as file:
with open('style.css', 'a+') as newfile:
content = newfile.read()
lines = file.readlines()
for line in lines:
if 'class="' in line:
to_replace = regex.findall(line)
for key in to_replace:
name='.'+key[0]+'-'+key[1]
prop=key[0]
value=key[1]
if prop and value in keyword:
var1 =('\n'+name+'{'+ '\n' + keyword[prop] + ': ' + keyword[value] + ';' + '\n'+'}')
if not var1 in content:
newfile.write(var1)
content += var1
content = newfile.read()
将读取带有样式的文件内容并将其保存到变量中。然后在每个新的var1
它将尝试在content
中找到它,如果var1
不在这里,它会将其写入文件并将其附加到content
变量。
输出:
.c-red{
color: #ed1a1a;
}
.bg-blue{
background: #60a8ff;
}