本文选自我集体创作的电子书 《Python黑魔法手册》

《Python黑魔法手册》在线浏览:http://magic.iswbm.com
Github 我的项目地址:https://github.com/iswbm/magi...


从一段指定的字符串中,获得冀望的数据,正常人都会想到正则表达式吧?

写过正则表达式的人都晓得,正则表达式入门不难,写起来也容易。

然而正则表达式简直没有可读性可言,保护起来,真的会让人抓狂,别以为这段正则是你写的就能够驾驭它,过个一个月你可能就不意识它了。

齐全能够说,天下苦正则久矣。

明天给你介绍一个好货色,能够让你解脱正则的噩梦,那就是 Python 中一个十分冷门的库 -- parse 。

1. 实在案例

拿一个最近应用 parse 的实在案例来举例说明。

上面是 ovs 一个条流表,当初我须要收集提取一个虚拟机(网口)里有多少流量、多少包流经了这条流表。也就是每个 in_port 对应的 n_bytes、n_packets 的值 。

cookie=0x9816da8e872d717d, duration=298506.364s, table=0, n_packets=480, n_bytes=20160, priority=10,arp,in_port="tapbbdf080b-c2" actions=resubmit(,24)

如果是你,你会怎么做呢?

先以逗号分隔开来,再以等号分隔取出值来?

你不防能够尝试一下,写进去的代码应该和我设想的一样,没有一丝感而言。

我来给你展现一下,我是怎么做的?

能够看到,我应用了一个叫做 parse 的第三方包,是须要自行装置的

$ python -m pip install parse

从下面这个案例中,你应该能感触到 parse 对于解析标准的字符串,是十分弱小的。

2. parse 的后果

parse 的后果只有两种后果:

  1. 没有匹配上,parse 的值为None
>>> parse("halo", "hello") is NoneTrue>>>
  1. 如果匹配上,parse 的值则 为 Result 实例
>>> parse("hello", "hello world")>>> parse("hello", "hello")<Result () {}>>>> 

如果你编写的解析规定,没有为字段定义字段名,也就是匿名字段, Result 将是一个 相似 list 的实例,演示如下:

>>> profile = parse("I am {}, {} years old, {}", "I am Jack, 27 years old, male")>>> profile<Result ('Jack', '27', 'male') {}>>>> profile[0]'Jack'>>> profile[1]'27'>>> profile[2]'male'

而如果你编写的解析规定,为字段定义了字段名, Result 将是一个 相似 字典 的实例,演示如下:

>>> profile = parse("I am {name}, {age} years old, {gender}", "I am Jack, 27 years old, male")>>> profile<Result () {'gender': 'male', 'age': '27', 'name': 'Jack'}>>>> profile['name']'Jack'>>> profile['age']'27'>>> profile['gender']'male'

3. 反复利用 pattern

和应用 re 一样,parse 同样反对 pattern 复用。

>>> from parse import compile>>> >>> pattern = compile("I am {}, {} years old, {}")>>> pattern.parse("I am Jack, 27 years old, male")<Result ('Jack', '27', 'male') {}>>>> >>> pattern.parse("I am Tom, 26 years old, male")<Result ('Tom', '26', 'male') {}>

4. 类型转化

从下面的例子中,你应该能留神到,parse 在获取年龄的时候,变成了一个"27" ,这是一个字符串,有没有一种方法,能够在提取的时候就依照咱们的类型进行转换呢?

你能够这样写。

>>> from parse import parse>>> profile = parse("I am {name}, {age:d} years old, {gender}", "I am Jack, 27 years old, male")>>> profile<Result () {'gender': 'male', 'age': 27, 'name': 'Jack'}>>>> type(profile["age"])<type 'int'>

除了将其转为 整型,还有其余格局吗?

内置的格局还有很多,比方

匹配工夫

>>> parse('Meet at {:tg}', 'Meet at 1/2/2011 11:00 PM')<Result (datetime.datetime(2011, 2, 1, 23, 0),) {}>

更多类型请参考官网文档:

TypeCharacters MatchedOutput
lLetters (ASCII)str
wLetters, numbers and underscorestr
WNot letters, numbers and underscorestr
sWhitespacestr
SNon-whitespacestr
dDigits (effectively integer numbers)int
DNon-digitstr
nNumbers with thousands separators (, or .)int
%Percentage (converted to value/100.0)float
fFixed-point numbersfloat
FDecimal numbersDecimal
eFloating-point numbers with exponent e.g. 1.1e-10, NAN (all case insensitive)float
gGeneral number format (either d, f or e)float
bBinary numbersint
oOctal numbersint
xHexadecimal numbers (lower and upper case)int
tiISO 8601 format date/time e.g. 1972-01-20T10:21:36Z (“T” and “Z” optional)datetime
teRFC2822 e-mail format date/time e.g. Mon, 20 Jan 1972 10:21:36 +1000datetime
tgGlobal (day/month) format date/time e.g. 20/1/1972 10:21:36 AM +1:00datetime
taUS (month/day) format date/time e.g. 1/20/1972 10:21:36 PM +10:30datetime
tcctime() format date/time e.g. Sun Sep 16 01:03:52 1973datetime
thHTTP log format date/time e.g. 21/Nov/2011:00:07:11 +0000datetime
tsLinux system log format date/time e.g. Nov 9 03:37:44datetime
ttTime e.g. 10:21:36 PM -5:30time

5. 提取时去除空格

去除两边空格

>>> parse('hello {} , hello python', 'hello     world    , hello python')<Result ('    world   ',) {}>>>> >>> >>> parse('hello {:^} , hello python', 'hello     world    , hello python')<Result ('world',) {}>

去除右边空格

>>> parse('hello {:>} , hello python', 'hello     world    , hello python')<Result ('world   ',) {}>

去除左边空格

>>> parse('hello {:<} , hello python', 'hello     world    , hello python')<Result ('    world',) {}>

6. 大小写敏感开关

Parse 默认是大小写不敏感的,你写 hello 和 HELLO 是一样的。

如果你须要辨别大小写,那能够加个参数,演示如下:

>>> parse('SPAM', 'spam')<Result () {}>>>> parse('SPAM', 'spam') is NoneFalse>>> parse('SPAM', 'spam', case_sensitive=True) is NoneTrue

7. 匹配字符数

准确匹配:指定最大字符数

>>> parse('{:.2}{:.2}', 'hello')  # 字符数不符>>> >>> parse('{:.2}{:.2}', 'hell')   # 字符数相符<Result ('he', 'll') {}>

含糊匹配:指定最小字符数

>>> parse('{:.2}{:2}', 'hello') <Result ('h', 'ello') {}>>>> >>> parse('{:2}{:2}', 'hello') <Result ('he', 'llo') {}>

若要在精准/含糊匹配的模式下,再进行格局转换,能够这样写

>>> parse('{:2}{:2}', '1024') <Result ('10', '24') {}>>>> >>> >>> parse('{:2d}{:2d}', '1024') <Result (10, 24) {}>

8. 三个重要属性

Parse 里有三个十分重要的属性

  • fixed:利用地位提取的匿名字段的元组
  • named:寄存有命名的字段的字典
  • spans:寄存匹配到字段的地位

上面这段代码,带你理解他们之间有什么不同

>>> profile = parse("I am {name}, {age:d} years old, {}", "I am Jack, 27 years old, male")>>> profile.fixed('male',)>>> profile.named{'age': 27, 'name': 'Jack'}>>> profile.spans{0: (25, 29), 'age': (11, 13), 'name': (5, 9)}>>> 

9. 自定义类型的转换

匹配到的字符串,会做为参数传入对应的函数

比方咱们之前讲过的,将字符串转整型

>>> parse("I am {:d}", "I am 27")<Result (27,) {}>>>> type(_[0])<type 'int'>>>> 

其等价于

>>> def myint(string):...     return int(string)... >>> >>> >>> parse("I am {:myint}", "I am 27", dict(myint=myint))<Result (27,) {}>>>> type(_[0])<type 'int'>>>>

利用它,咱们能够定制很多的性能,比方我想把匹配的字符串弄成全大写

>>> def shouty(string):...    return string.upper()...>>> parse('{:shouty} world', 'hello world', dict(shouty=shouty))<Result ('HELLO',) {}>>>>

10 总结一下

parse 库在字符串解析解决场景中提供的便当,肉眼可见,上手简略。

在一些简略的场景中,应用 parse 可比应用 re 去写正则开发效率不晓得高几个 level,用它写进去的代码富裕美感,可读性高,前期保护起代码来一点压力也没有,举荐你应用。