如何使用watchdog在每次使用某个单词修改文件时运行脚本?

2024-04-19 13:29:05 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,下面的脚本在HTML文件中查找关键字,并将找到的关键字的值写入文件style.css

from collections import OrderedDict
keyword = {
"row": '''
    .row {
    display: -ms-flexbox;
    display: flex; 
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-right: -15px;
    margin-left: -15px;
    }'''
    #etc
        }   

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 = line.split('"')[1].split()
            to_replace = OrderedDict.fromkeys(to_replace)
            for key in to_replace:
                if key in keyword:
                    newfile.write(keyword[key])
                    keyword[key] = ''

HTML文件:

<div class="row">some content</div>
<div class="row">some content2</div> etc

输出在style.css

.row {
        display: -ms-flexbox;
        display: flex; 
        -ms-flex-wrap: wrap;
        flex-wrap: wrap;
        margin-right: -15px;
        margin-left: -15px;
        }

注意:row用html编写了两次,但只以样式显示了一次。你知道吗

如何在每次保存文件index.html并从字典中找到某个关键字时运行代码(使用监视程序on_modified事件)? 另外,如何防止在style.css中重复css命令?


Tags: 文件tokeyinmargindivstyledisplay