成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

再見,正則表達式

開發 前端
從一段指定的字符串中,取得期望的數據,正常人都會想到正則表達式吧?寫過正則表達式的人都知道,正則表達式入門不難,寫起來也容易。

 [[340693]]

從一段指定的字符串中,取得期望的數據,正常人都會想到正則表達式吧?

寫過正則表達式的人都知道,正則表達式入門不難,寫起來也容易。

但是正則表達式幾乎沒有可讀性可言,維護起來,真的會讓人抓狂,別以為這段正則是你寫的就可以駕馭它,過個一個月你可能就不認識它了。

完全可以說,天下苦正則久矣。

今天給你介紹一個好東西,可以讓你擺脫正則的噩夢,那就是 Python 中一個非常冷門的庫 -- parse 。

1. 真實案例

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

下面是 ovs 一個條流表,現在我需要收集提取一個虛擬機(網口)里有多少流量、多少包流經了這條流表。也就是每個 in_port 對應的 n_bytes、n_packets 的值 。

  1. cookie=0x9816da8e872d717d, duration=298506.364s, table=0, n_packets=480, n_bytes=20160, priority=10,ip,in_port="tapbbdf080b-c2" actions=NORMAL 

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

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

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

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

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

  1. $ python -m pip install parse 

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

2. parse 的結果

parse 的結果只有兩種結果:

沒有匹配上,parse 的值為None

  1. >>> parse("halo""hello"is None 
  2. True 
  3. >>> 

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

  1. >>> parse("hello""hello world"
  2. >>> parse("hello""hello"
  3. <Result () {}> 
  4. >>>  

如果你編寫的解析規則,沒有為字段定義字段名,也就是匿名字段, Result 將是一個 類似 list 的實例,演示如下:

  1. >>> profile = parse("I am {}, {} years old, {}""I am Jack, 27 years old, male"
  2. >>> profile 
  3. <Result ('Jack''27''male') {}> 
  4. >>> profile[0] 
  5. 'Jack' 
  6. >>> profile[1] 
  7. '27' 
  8. >>> profile[2] 
  9. 'male' 

而如果你編寫的解析規則,為字段定義了字段名, Result 將是一個 類似 字典 的實例,演示如下:

  1. >>> profile = parse("I am {name}, {age} years old, {gender}""I am Jack, 27 years old, male"
  2. >>> profile 
  3. <Result () {'gender''male''age''27''name''Jack'}> 
  4. >>> profile['name'
  5. 'Jack' 
  6. >>> profile['age'
  7. '27' 
  8. >>> profile['gender'
  9. 'male' 

3. 重復利用 pattern

和使用 re 一樣,parse 同樣支持 pattern 復用。

  1. >>> from parse import compile 
  2. >>>  
  3. >>> pattern = compile("I am {}, {} years old, {}"
  4. >>> pattern.parse("I am Jack, 27 years old, male"
  5. <Result ('Jack''27''male') {}> 
  6. >>>  
  7. >>> pattern.parse("I am Tom, 26 years old, male"
  8. <Result ('Tom''26''male') {}> 

4. 類型轉化

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

你可以這樣寫。

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

除了將其轉為 整型,還有其他格式嗎?

內置的格式還有很多,比如

匹配時間

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

更多類型請參考官方文檔:

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. 提取時去除空格

去除兩邊空格

  1. >>> parse('hello {} , hello python''hello     world    , hello python'
  2. <Result ('    world   ',) {}> 
  3. >>>  
  4. >>>  
  5. >>> parse('hello {:^} , hello python''hello     world    , hello python'
  6. <Result ('world',) {}> 

去除左邊空格

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

去除右邊空格

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

6. 大小寫敏感開關

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

如果你需要區分大小寫,那可以加個參數,演示如下:

  1. >>> parse('SPAM''spam'
  2. <Result () {}> 
  3. >>> parse('SPAM''spam'is None 
  4. False 
  5. >>> parse('SPAM''spam', case_sensitive=Trueis None 
  6. True 

7. 匹配字符數

精確匹配:指定最大字符數

  1. >>> parse('{:.2}{:.2}''hello')  # 字符數不符 
  2. >>>  
  3. >>> parse('{:.2}{:.2}''hell')   # 字符數相符 
  4. <Result ('he''ll') {}> 

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

  1. >>> parse('{:.2}{:2}''hello')  
  2. <Result ('h''ello') {}> 
  3. >>>  
  4. >>> parse('{:2}{:2}''hello')  
  5. <Result ('he''llo') {}> 

若要在精準/模糊匹配的模式下,再進行格式轉換,可以這樣寫

  1. >>> parse('{:2}{:2}''1024')  
  2. <Result ('10''24') {}> 
  3. >>>  
  4. >>>  
  5. >>> parse('{:2d}{:2d}''1024')  
  6. <Result (10, 24) {}> 

8. 三個重要屬性

Parse 里有三個非常重要的屬性

  • fixed:利用位置提取的匿名字段的元組
  • named:存放有命名的字段的字典
  • spans:存放匹配到字段的位置

下面這段代碼,帶你了解他們之間有什么不同

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

9. 自定義類型的轉換

匹配到的字符串,會做為參數傳入對應的函數

比如我們之前講過的,將字符串轉整型

  1. >>> parse("I am {:d}""I am 27"
  2. <Result (27,) {}> 
  3. >>> type(_[0]) 
  4. <type 'int'
  5. >>>  

其等價于

  1. >>> def myint(string): 
  2. ...     return int(string) 
  3. ...  
  4. >>>  
  5. >>>  
  6. >>> parse("I am {:myint}""I am 27", dict(myint=myint)) 
  7. <Result (27,) {}> 
  8. >>> type(_[0]) 
  9. <type 'int'
  10. >>> 

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

  1. >>> def shouty(string): 
  2. ...    return string.upper() 
  3. ... 
  4. >>> parse('{:shouty} world''hello world', dict(shouty=shouty)) 
  5. <Result ('HELLO',) {}> 
  6. >>> 

10 總結一下

parse 庫在字符串解析處理場景中提供的便利,肉眼可見,上手簡單。

在一些簡單的場景中,使用 parse 可比使用 re 去寫正則開發效率不知道高幾個 level,用它寫出來的代碼富有美感,可讀性高,后期維護起代碼來一點壓力也沒有,推薦你使用。

本文轉載自微信公眾號「 Python編程時光」,可以通過以下二維碼關注。轉載本文請聯系 Python編程時光公眾號。

 

責任編輯:武曉燕 來源: Python編程時光
相關推薦

2018-09-27 15:25:08

正則表達式前端

2024-09-14 09:18:14

Python正則表達式

2016-11-10 16:21:22

Java 正則表達式

2009-09-16 17:15:57

正則表達式引擎

2022-01-04 11:35:03

Linux Shel正則表達式Linux

2023-09-13 08:12:45

2010-03-25 18:25:36

Python正則表達式

2017-05-12 10:47:45

Linux正則表達式程序基礎

2022-03-28 06:19:14

正則表達式開發

2021-01-27 11:34:19

Python正則表達式字符串

2009-02-18 09:48:20

正則表達式Java教程

2019-07-17 15:45:47

正則表達式字符串前端

2009-09-16 18:19:34

正則表達式組

2011-06-02 12:34:16

正則表達式

2012-04-28 15:22:46

PHP

2011-06-16 16:05:23

正則表達式

2010-07-13 17:03:53

Perl正則表達式

2010-07-14 09:01:18

Perl正則表達式

2010-07-19 10:40:16

Perl正則表達式

2010-08-09 14:43:25

Flex正則表達式
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 国产伦一区二区三区 | 视频一区二区三区在线观看 | 四虎影| 国产成人精品一区 | 一区二区三区精品视频 | 亚洲狠狠爱 | 日韩精品一区在线 | 亚洲一区二区不卡在线观看 | 看一级黄色毛片 | 国产高清无av久久 | 99精品国产一区二区青青牛奶 | 久久精品国产亚洲 | 在线看av网址| 日韩视频区 | 久久久亚洲 | 欧美日韩亚洲三区 | 精品国产伦一区二区三区观看体验 | 操夜夜| 日韩成人av在线 | 日韩av第一页| 国产小视频在线 | 日韩精品视频在线观看一区二区三区 | 欧美 日韩 中文 | 国产一区二区三区 | 久久久www成人免费无遮挡大片 | 欧美精品网站 | 精品视频在线免费观看 | 亚洲成人一级 | 亚洲欧美综合精品另类天天更新 | 亚洲在线久久 | 91麻豆精品国产91久久久久久 | 成人在线精品视频 | 日韩在线观看 | 中文字幕日韩欧美一区二区三区 | 国产精品一区二区三区免费观看 | 国产精品伦一区二区三级视频 | 精品永久 | 欧美精品成人 | 欧美日韩一区二区三区四区五区 | 97精品超碰一区二区三区 | 成人在线视频观看 |