欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

不需要用到正則的Python文本解析庫(kù)parse

 更新時(shí)間:2021年10月25日 17:06:52   作者:寫(xiě)代碼的明哥  
今天給你介紹一個(gè)好東西,可以讓你擺脫正則的噩夢(mèng),那就是 Python 中一個(gè)非常冷門(mén)的庫(kù)parse。有需要的朋友可以借鑒參考下,希望能夠有所幫助

從一段指定的字符串中,取得期望的數(shù)據(jù),正常人都會(huì)想到正則表達(dá)式吧?

寫(xiě)過(guò)正則表達(dá)式的人都知道,正則表達(dá)式入門(mén)不難,寫(xiě)起來(lái)也容易。

但是正則表達(dá)式幾乎沒(méi)有可讀性可言,維護(hù)起來(lái),真的會(huì)讓人抓狂,別以為這段正則是你寫(xiě)的就可以駕馭它,過(guò)個(gè)一個(gè)月你可能就不認(rèn)識(shí)它了。

完全可以說(shuō),天下苦正則久矣。

1. 真實(shí)案例

拿一個(gè)最近使用 parse 的真實(shí)案例來(lái)舉例說(shuō)明。

下面是 ovs 一個(gè)條流表,現(xiàn)在我需要收集提取一個(gè)虛擬機(jī)(網(wǎng)口)里有多少流量、多少包流經(jīng)了這條流表。也就是每個(gè) in_port 對(duì)應(yīng)的 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

如果是你,你會(huì)怎么做呢?

先以逗號(hào)分隔開(kāi)來(lái),再以等號(hào)分隔取出值來(lái)?

你不防可以嘗試一下,寫(xiě)出來(lái)的代碼應(yīng)該和我想象的一樣,沒(méi)有一絲美感而言。

我來(lái)給你展示一下,我是怎么做的?

可以看到,我使用了一個(gè)叫做 parse 的第三方包,是需要自行安裝的

$ python -m pip install parse

從上面這個(gè)案例中,你應(yīng)該能感受到 parse 對(duì)于解析規(guī)范的字符串,是非常強(qiáng)大的。

2. parse 的結(jié)果

parse 的結(jié)果只有兩種結(jié)果:

1.沒(méi)有匹配上,parse 的值為None

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

如果匹配上,parse 的值則 為 Result 實(shí)例

>>> parse("hello", "hello world")
>>> parse("hello", "hello")
<Result () {}>
>>> 

如果你編寫(xiě)的解析規(guī)則,沒(méi)有為字段定義字段名,也就是匿名字段, Result 將是一個(gè) 類(lèi)似 list 的實(shí)例,演示如下:

>>> 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'

而如果你編寫(xiě)的解析規(guī)則,為字段定義了字段名, Result 將是一個(gè) 類(lèi)似 字典 的實(shí)例,演示如下:

>>> 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. 重復(fù)利用 pattern

和使用 re 一樣,parse 同樣支持 pattern 復(fù)用。

>>> 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. 類(lèi)型轉(zhuǎn)化

從上面的例子中,你應(yīng)該能注意到,parse 在獲取年齡的時(shí)候,變成了一個(gè)"27" ,這是一個(gè)字符串,有沒(méi)有一種辦法,可以在提取的時(shí)候就按照我們的類(lèi)型進(jìn)行轉(zhuǎn)換呢?

你可以這樣寫(xiě)。

>>> 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'>

除了將其轉(zhuǎn)為 整型,還有其他格式嗎?

內(nèi)置的格式還有很多,比如

匹配時(shí)間

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

更多類(lèi)型請(qǐng)參考官方文檔:

Type Characters Matched Output
l Letters (ASCII) str
w Letters, numbers and underscore str
W Not letters, numbers and underscore str
s Whitespace str
S Non-whitespace str
d Digits (effectively integer numbers) int
D Non-digit str
n Numbers with thousands separators (, or .) int
% Percentage (converted to value/100.0) float
f Fixed-point numbers float
F Decimal numbers Decimal
e Floating-point numbers with exponent e.g. 1.1e-10, NAN (all case insensitive) float
g General number format (either d, f or e) float
b Binary numbers int
o Octal numbers int
x Hexadecimal numbers (lower and upper case) int
ti ISO 8601 format date/time e.g. 1972-01-20T10:21:36Z (“T” and “Z” optional) datetime
te RFC2822 e-mail format date/time e.g. Mon, 20 Jan 1972 10:21:36 +1000 datetime
tg Global (day/month) format date/time e.g. 20/1/1972 10:21:36 AM +1:00 datetime
ta US (month/day) format date/time e.g. 1/20/1972 10:21:36 PM +10:30 datetime
tc ctime() format date/time e.g. Sun Sep 16 01:03:52 1973 datetime
th HTTP log format date/time e.g. 21/Nov/2011:00:07:11 +0000 datetime
ts Linux system log format date/time e.g. Nov 9 03:37:44 datetime
tt Time e.g. 10:21:36 PM -5:30 time

5. 提取時(shí)去除空格

去除兩邊空格

>>> 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. 大小寫(xiě)敏感開(kāi)關(guān)

Parse 默認(rèn)是大小寫(xiě)不敏感的,你寫(xiě) hello 和 HELLO 是一樣的。

如果你需要區(qū)分大小寫(xiě),那可以加個(gè)參數(shù),演示如下:

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

7. 匹配字符數(shù)

精確匹配:指定最大字符數(shù)

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

模糊匹配:指定最小字符數(shù)

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

若要在精準(zhǔn)/模糊匹配的模式下,再進(jìn)行格式轉(zhuǎn)換,可以這樣寫(xiě)

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

8. 三個(gè)重要屬性

Parse 里有三個(gè)非常重要的屬性

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. 自定義類(lèi)型的轉(zhuǎn)換

匹配到的字符串,會(huì)做為參數(shù)傳入對(duì)應(yīng)的函數(shù)

比如我們之前講過(guò)的,將字符串轉(zhuǎn)整型

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

其等價(jià)于

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

利用它,我們可以定制很多的功能,比如我想把匹配的字符串弄成全大寫(xiě)

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

10 總結(jié)一下

parse 庫(kù)在字符串解析處理場(chǎng)景中提供的便利,肉眼可見(jiàn),上手簡(jiǎn)單。

在一些簡(jiǎn)單的場(chǎng)景中,使用 parse 可比使用 re 去寫(xiě)正則開(kāi)發(fā)效率不知道高幾個(gè) level,用它寫(xiě)出來(lái)的代碼富有美感,可讀性高,后期維護(hù)起代碼來(lái)一點(diǎn)壓力也沒(méi)有,推薦你使用。

以上就是不需要用到正則的Python文本解析庫(kù)parse的詳細(xì)內(nèi)容,更多關(guān)于Python文本解析庫(kù)parse的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python基于Tensor FLow的圖像處理操作詳解

    Python基于Tensor FLow的圖像處理操作詳解

    這篇文章主要介紹了Python基于Tensor FLow的圖像處理操作,結(jié)合實(shí)例形式分析了Python基于Tensor FLow操作圖像解碼、縮放、剪切、翻轉(zhuǎn)、調(diào)整對(duì)比度、明度、飽和度等相關(guān)操作技巧,需要的朋友可以參考下
    2020-01-01
  • python中操作文件的模塊的方法總結(jié)

    python中操作文件的模塊的方法總結(jié)

    在本篇文章里小編給大家整理的是一篇關(guān)于python中操作文件的模塊的方法總結(jié),有需要的朋友們可以學(xué)習(xí)參考下。
    2021-02-02
  • python3.6環(huán)境安裝+pip環(huán)境配置教程圖文詳解

    python3.6環(huán)境安裝+pip環(huán)境配置教程圖文詳解

    這篇文章主要介紹了python3.6環(huán)境安裝+pip環(huán)境配置教程圖文詳解,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-06-06
  • Python 爬蟲(chóng)模擬登陸知乎

    Python 爬蟲(chóng)模擬登陸知乎

    這篇文章主要介紹了Python 爬蟲(chóng)模擬登陸知乎的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2016-09-09
  • 39條Python語(yǔ)句實(shí)現(xiàn)數(shù)字華容道

    39條Python語(yǔ)句實(shí)現(xiàn)數(shù)字華容道

    這篇文章主要為大家詳細(xì)介紹了39條Python語(yǔ)句實(shí)現(xiàn)數(shù)字華容道,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-04-04
  • python兩種注釋用法的示例

    python兩種注釋用法的示例

    這篇文章主要介紹了python兩種注釋用法的示例,幫助大家開(kāi)始學(xué)習(xí)和使用python 注釋?zhuān)信d趣的朋友可以了解下
    2020-10-10
  • Python?Django源碼運(yùn)行過(guò)程解析

    Python?Django源碼運(yùn)行過(guò)程解析

    這篇文章主要介紹了Python?Django源碼運(yùn)行過(guò)程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-08-08
  • Python設(shè)計(jì)模式行為型責(zé)任鏈模式

    Python設(shè)計(jì)模式行為型責(zé)任鏈模式

    這篇文章主要介紹了Python設(shè)計(jì)模式行為型責(zé)任鏈模式,責(zé)任鏈模式將能處理請(qǐng)求的對(duì)象連成一條鏈,并沿著這條鏈傳遞該請(qǐng)求,直到有一個(gè)對(duì)象處理請(qǐng)求為止,避免請(qǐng)求的發(fā)送者和接收者之間的耦合關(guān)系,下圍繞改內(nèi)容介紹具有一點(diǎn)的參考價(jià)值,需要的朋友可以參考下
    2022-02-02
  • Python 使用pandas實(shí)現(xiàn)查詢和統(tǒng)計(jì)示例詳解

    Python 使用pandas實(shí)現(xiàn)查詢和統(tǒng)計(jì)示例詳解

    這篇文章主要為大家介紹了Python 使用pandas實(shí)現(xiàn)查詢和統(tǒng)計(jì)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08
  • python多版本工具miniconda的配置優(yōu)化實(shí)現(xiàn)

    python多版本工具miniconda的配置優(yōu)化實(shí)現(xiàn)

    通過(guò)Miniconda,您可以輕松地創(chuàng)建和管理多個(gè)Python環(huán)境,同時(shí)確保每個(gè)環(huán)境具有所需的依賴(lài)項(xiàng)和軟件包,本文主要介紹了python多版本工具miniconda的配置優(yōu)化實(shí)現(xiàn),感興趣的可以了解一下
    2024-01-01

最新評(píng)論