溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用不需要用到正則的Python文本解析庫parse

發(fā)布時間:2021-10-26 09:10:49 來源:億速云 閱讀:230 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“如何使用不需要用到正則的Python文本解析庫parse”,在日常操作中,相信很多人在如何使用不需要用到正則的Python文本解析庫parse問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何使用不需要用到正則的Python文本解析庫parse”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

1. 真實案例

拿一個最近使用 parse 的真實案例來舉例說明。

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

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

先以逗號分隔開來,再以等號分隔取出值來?

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

我來給你展示一下,我是怎么做的?

如何使用不需要用到正則的Python文本解析庫parse

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

$ python -m pip install parse

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

2. parse 的結(jié)果

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

1.沒有匹配上,parse 的值為None

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

如果匹配上,parse 的值則 為 Result 實例

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

如果你編寫的解析規(guī)則,沒有為字段定義字段名,也就是匿名字段, 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'

而如果你編寫的解析規(guī)則,為字段定義了字段名, 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. 重復(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. 類型轉(zhuǎn)化

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

你可以這樣寫。

>>> 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)置的格式還有很多,比如

匹配時間

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

Parse 默認是大小寫不敏感的,你寫 hello 和 HELLO 是一樣的。

如果你需要區(qū)分大小寫,那可以加個參數(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)/模糊匹配的模式下,再進行格式轉(zhuǎn)換,可以這樣寫

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

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

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

>>> 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',) {}>
>>>

到此,關(guān)于“如何使用不需要用到正則的Python文本解析庫parse”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI