python: 把 html中的 “40px” 转换为 “2.5em”

该代码段展示了一个Python函数,将CSS中的像素(px)单位转换为相对单位em。通过正则表达式匹配px值,并进行换算。整个过程包括读取文件,替换字符串中的px单位为em,然后将结果写入新的文件中,实现静态资源的尺寸适配。
摘要由CSDN通过智能技术生成

import re

def px_2_em(matched):
  value = matched.group(0)
  n= int(value[0:-2]) / 16
  return str(n) + 'em'

# replace: {n}px / 16 -> {x}em
def replace(string):
  regexp = r'[0-9]+px'
  result = re.sub( regexp, px_2_em , string)
  return result

def start(originFile, saveFle):
  with open(originFile, 'r') as f:
    # get string
    string = f.read()
    # replace
    res = replace(string)
    # write
    newFile = open(saveFle, "w+")
    newFile.write(res)
    newFile.close()
    # close file
    f.close()


start('./table.html','./table_em.html')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值