python自动化之转换数据持续更新:【内向即蛆虫--屠雅倩】


def create_defaulttime(format='%Y-%m-%d %H:%M:%S'):
    '''創建默認時間'''
    return datetime(1970, 1, 1).strftime(format)

def data_today(date: 'str'):
    '''將年月周日轉換成天'''
    date = str(date)
    unit = 1
    if '周' in date:
        unit = 7
    elif '月' in date:
        unit = 30
    elif '年' in date:
        unit = 360


    terms = re.compile('\d+').search(date).group()
    return int(terms) * unit

def timestamp_transform(timestamp: 'int', format='%Y-%m-%d %H:%M:%S'):
    '''10位或13位時間戳轉換'''
    timestamp_len = len(str(timestamp))
    if timestamp_len == 13:
        timestamp /= 1000
        return datetime.fromtimestamp(timestamp).strftime(format)
    elif timestamp_len == 10:
        time_local = time.localtime(timestamp)
        return time.strftime("%Y-%m-%d %H:%M:%S", time_local)

def localtime_totimestamp(count: 'int'):
    '''本地時間轉換成13位時間戳或者10位時間戳'''
    if count == 10:
        return str(time.time()).replace('.', '')[:10]
    else:
        return str(time.time()).replace('.', '')[:13]

def formdata_todictdata(parameter:'str'):

    '''将fiddler中的post参数数据转化为dict数据
    parmater='timestamp=1516876058823&app_key=lmw_product_pc&app_version=3.0.0'
    res:{'timestamp': '1516876058823', 'app_version': '3.0.0', 'app_key': 'lmw_product_pc'}
    '''
    data=parameter.split('&')
    dict_data=dict((map(lambda data:data.split('='),data)))
    return dict_data


def get_nongli(container: 'list' = [1998, 2, 3]):
    '''农历转公历
    container=[1998,2,3]
    return [1998, 3, 1]
    '''
    converter = LunarSolarConverter.LunarSolarConverter()
    year, month, day = container
    lunar = LunarSolarConverter.Lunar(year, month, day, isleap=False)
    solar = converter.LunarToSolar(lunar)
    resdata = vars(solar)
    return [resdata['solarYear'], resdata['solarMonth'], resdata['solarDay']]


def get_md5(text):
    """返回md5值"""
    return hashlib.md5(text.encode()).hexdigest()


def dictkeyvalue_transform(mydict: 'dict'):
    """键值对互相转换"""
    mydict_new = dict(zip(mydict.values(), mydict.keys()))
    return mydict_new


def semiangle(tabulation: 'object()'):
    ''' 全角转半角'''
    codes = []
    for char in tabulation:
        code = ord(char)
        if code == 12288:
            code = 32
        elif (65281 <= code <= 65374):
            code -= 65248
        codes.append(code)
    return ''.join([chr(code) for code in codes])


def correct_encode(tabulation):
    '''返回无编码错误的文本'''
    return str(tabulation).encode('gbk', 'ignore').decode('gbk')


def decipher_base64(text: 'str'):
    '''转换base64为二进制数据'''
    return base64.b64decode(text)


def str_tobytes(text: 'str'):
    '''字符串转字节'''
    return text.encode('utf-8')


def bytes_tostr(text: 'bytes()'):
    '''字节转字符串
    text=bytes_tostr(text=b'made in \xe4\xb8\xad\xe5\x9b\xbd')
    res=made in 中国
    '''
    return text.decode('utf-8')


def sexteenstr_tobytes(text: 'str'):
    '''16进制字符串转换成10进制字节'''
    return bytes.fromhex(text)


def tentybes_toint(text: 'bytes()', byteorder: '字节排序' = 'big'):
    '''10进制字节转换成整数'''
    return int.from_bytes(text, byteorder=byteorder)


def int_toascii(text: 'int'):
    '''整数转ASCII字符'''
    return chr(text)


def str_tounicode(text: 'str'):
    '''字符串转unicode'''
    return text.encode('unicode-escape')


def unicode_tostr(text: ''):
    '''unicode转str
    text=b'\\u4e2d\\u56fd\\u7684\\u9886\\u571f')
    res=中国的领土
    '''
    return text.decode('unicode-escape')


def chinese_tohtml(text: 'str' = None):
    '''中文转html格式
    text=周杰伦
    res=%E5%91%A8%E6%9D%B0%E4%BC%A6
    '''
    return quote(text)


def html_tochinese(text: 'str' = None):
    # text='https://data-gkcx.eol.cn/soudaxue/queryProvinceScore.html?messtype=jsonp&callback=jQuery18306090234935406156_1512819801010&provinceforschool=%E5%8C%97%E4%BA%AC&schooltype=%E6%99%AE%E9%80%9A%E6%9C%AC%E7%A7%91&page=1&size=10&keyWord=&schoolproperty=%E7%BB%BC%E5%90%88%E7%B1%BB&schoolflag=&province=&fstype=&zhaoshengpici=&fsyear=&_=1512819803263'
    '''html格式转成中文
    text='%E5%91%A8%E6%9D%B0%E4%BC%A6'
    res=周杰伦
    '''
    # text='https://data-gkcx.eol.cn/soudaxue/queryProvinceScore.html?messtype=jsonp&callback=jQuery18306551941833402415_1512822071372&provinceforschool=%E5%8C%97%E4%BA%AC&schooltype=%E9%AB%98%E8%81%8C%E9%AB%98%E4%B8%93&page=3&size=10&keyWord=&schoolproperty=%E7%BB%BC%E5%90%88%E7%B1%BB&schoolflag=&province=&fstype=&zhaoshengpici=&fsyear=&_=1512822072474 '
    return unquote(text)


def chinesenumber_tonumber(uchars_chinese: ''):
    """
    uchars_chinese=二百八十一
    res=281
    """
    common_used_numerals_tmp = {'零': 0, '一': 1, '二': 2, '两': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9,
                                '十': 10, '百': 100, '千': 1000, '万': 10000, '亿': 100000000}
    common_used_numerals = {}
    for key in common_used_numerals_tmp:
        common_used_numerals[key] = common_used_numerals_tmp[key]
    total = 0
    r = 1
    for i in range(len(uchars_chinese) - 1, -1, -1):
        val = common_used_numerals.get(uchars_chinese[i])
        if val >= 10 and i == 0:
            if val > r:
                r = val
                total = total + val
            else:
                r = r * val
        elif val >= 10:
            if val > r:
                r = val
            else:
                r = r * val
        else:
            total = total + r * val
    return total

猜你喜欢

转载自blog.csdn.net/qq_37995231/article/details/79260645
今日推荐