网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

怎么使用parse

这篇文章主要讲解了“怎么使用parse”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用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,ip,in_port="tapbbdf080b-c2" actions=NORMAL

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

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

你不防可以尝试一下,写出来的代码应该和我想象的一样,没有一丝美感而言。

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

可以看到,我使用了一个叫做 parse 的第三方包,是需要自行安装的

$ python -m pip install parse

从上面这个案例中,你应该能感受到 parse 对于解析规范的字符串,是非常强大的。

2. parse 的结果

parse 的结果只有两种结果:

没有匹配上,parse 的值为None

>>> parse("halo", "hello") is None True >>>

如果匹配上,parse 的值则 为 Result 实例

>>> parse("hello", "hello world") >>> parse("hello", "hello")  >>>

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

>>> profile = parse("I am {}, {} years old, {}", "I am Jack, 27 years old, male") >>> profile  >>> 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  >>> 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")  >>>  >>> pattern.parse("I am Tom, 26 years old, 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  >>> type(profile["age"]) 

除了将其转为 整型,还有其他格式吗?

内置的格式还有很多,比如

匹配时间

>>> parse('Meet at {:tg}', 'Meet at 1/2/2011 11:00 PM') 

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

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')  >>>  >>>  >>> parse('hello {:^} , hello python', 'hello     world    , hello python') 

去除左边空格

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

去除右边空格

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

6. 大小写敏感开关

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

如果你需要区分大小写,那可以加个参数,演示如下:

>>> parse('SPAM', 'spam')  >>> parse('SPAM', 'spam') is None False >>> parse('SPAM', 'spam', case_sensitive=True) is None True

7. 匹配字符数

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

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

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

>>> parse('{:.2}{:2}', 'hello')   >>>  >>> parse('{:2}{:2}', 'hello')  

若要在精准/模糊匹配的模式下,再进行格式转换,可以这样写

>>> parse('{:2}{:2}', '1024')   >>>  >>>  >>> parse('{:2d}{:2d}', '1024')  

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")  >>> type(_[0])  >>>

其等价于

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

利用它,我们可以定制很多的功能,比如我想把匹配的字符串弄成全大写

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

感谢各位的阅读,以上就是“怎么使用parse”的内容了,经过本文的学习后,相信大家对怎么使用parse这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!


新闻名称:怎么使用parse
网站网址:http://bjjierui.cn/article/pigjsh.html

其他资讯