zoukankan      html  css  js  c++  java
  • python 转换容量单位 实现ls -h功能

    功能1
    把字节转换自适应转为其他单位(ls -h),超过1024投入高一级的区间,不足1024投入本级区间,如1000K是一个合理值,1030K就应该转换为1M,2050K应该转换为2M
    功能2
    把其他单位转换为字节
    #!/usr/bin/python3
    # -*- coding: utf-8 -*-
    import re
    
    
    def size_b_to_other(size):
        units = ['B', 'KB', 'MB', 'GB', 'TB']
        # 处理异常
        if size <= 0:
            return False
    
        # 遍历单位的位置并用取整除赋值
        for unit in units:
            if size >= 1024:
                size //= 1024
            else:
                size_h = '{} {}'.format(size, unit)
                return size_h
    
        size_h = '{} {}'.format(size, unit)
        return size_h
    
    
    def size_other_to_b(size, unit):
        units = ['B', 'KB', 'MB', 'GB', 'TB']
        # 处理异常
        if size <= 0:
            return False
    
        # 找出单位的索引位置
        nu = units.index(unit)
    
        # 根据索引位置次幂在乘以系数
        size_h = int(size) * 1024 ** nu
        return int(size_h)
    
    
    if __name__ == '__main__':
        """
        这里可以实现字节B转换其他单位或者其他单位转字节B,输入容量数字和单位后自动识别转换
        格式为10000B或者10M、1gb、20kb
        """
        data = input("请输要转换的容量和单位:")
        # 忽略大小写敏感
        size = re.sub("D", "", data)
        size = int(size)
        unit = ''.join(re.findall(r'[A-Za-z]', str.upper(data)))
        if unit == "B":
            result = size_b_to_other(size)
        else:
            # 支持单位简写
            if len(unit) == 1 :
                unit = unit + "B"
            result = size_other_to_b(size, unit)
    
        print(result)
  • 相关阅读:
    二分查找
    苹果开发人员账号注冊流程
    cocos2d_android 瞬间动作
    Qt多线程学习:创建多线程
    Java模式(适配器模式)
    代理方法keywordAction与Fun的使用
    装饰者模式
    编写你自己的单点登录(SSO)服务
    4种Java引用浅解
    strtok和strtok_r
  • 原文地址:https://www.cnblogs.com/37yan/p/10710695.html
Copyright © 2011-2022 走看看