您的位置:首页 > 编程语言 > Python开发

python 关于格式转换的处理方法dict.itervalues() + dict.format()

2017-08-12 11:57 323 查看
问题:

如何处理相同内容,不同显示格式的统一处理?

解决方案:

采用dict.itervalues()方法,获取每一个不同的格式类型

采用re.search(格式,内容)方法,找到对应的格式,并将匹配到的内容存储为一个元组

采用dict.format(*元组)方法,将该元组格式化为统一的格式,并输出

讨论:

格式必须事先全部确定,缺少灵活性

# -*- coding:utf-8 -*-

import os

import sys

import re

print u"mac地址转换"

print u'采用pattens匹配的方法实现'

mac1 = '00.11.22.33.44.55'

mac2 = '00:11:22:33:44:55'

mac3 = '0011.2233.4455'

mac4 = '00-11-22-33-44-55'

mac5 = '001122334455'

search_pattens = {

        0: r"(\w{2})(\w{2})(\w{2})(\w{2})(\w{2})(\w{2})",

        1: r"(\w{2})(\w{2})\.(\w{2})(\w{2})\.(\w{2})(\w{2})",

        2: r"(\w{2}):(\w{2}):(\w{2}):(\w{2}):(\w{2}):(\w{2})",

        3: r"(\w{2})-(\w{2})-(\w{2})-(\w{2})-(\w{2})-(\w{2})",

        4: r"(\w{2})\.(\w{2})\.(\w{2})\.(\w{2})\.(\w{2})\.(\w{2})"

    }

format_pattens = {

        0: "{0}{1}{2}{3}{4}{5}",

        1: "{0}{1}.{2}{3}.{4}{5}",

        2: "{0}:{1}:{2}:{3}:{4}:{5}",

        3: "{0}-{1}-{2}-{3}-{4}-{5}",

        4: "{0}.{1}.{2}.{3}.{4}.{5}"

    }

def mac_convert(mac, mac_type=1):

        """

        Args:

            mac: 输入的MAC,格式自动判断

            mac_type: 输出MAC的格式,默认转换成type1。

               | 0 : 010203040506 |

               | 1 : 0102.0304.0506 |

               | 2 : 01:02:03:04:05:06 |

               | 3 : 01-02-03-04-05-06 |

               | 4 : 01.02.03.04.05.06 |

        Returns: 输出的MAC大小写不做改变

        """

        data = []

        for sp in search_pattens.itervalues():

            m = re.search(sp, mac)

            if m:

                data = m.groups() # 返回元组

                print m.group() # 返回数值

                break

        if len(data) is not 6:

            print u"[MAC CONVERT ERROR] 输入MAC %s 格式不正确" % mac

            return ""

        mac_type = int(mac_type)

        fp = format_pattens[mac_type]

        return fp.format(*data)

if __name__ == '__main__':

    print mac1

    print mac_convert(mac1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python