Python模組:Re模組、附軟體開發目錄規範

來源:互聯網
上載者:User

標籤:mat   定位   from   語句   知識點   詳細   安裝   for   make   

Re模組:(Regex)

Regex就是字串的匹配規則

Regex在多數程式設計語言裡都有相應的支援,Python裡面對應的模組時re

常用的運算式規則:(都需要記住)

“ . ”   #  預設匹配除\n之外的任意一個字元,若指定flag DOTALL,則匹配任一字元,包括換行

“ ^ ”  #  匹配字元開頭,若指定flags MULTILINE,這種也可以匹配上("^a","\nabc\neee",flags=re.MULTILINE)(即:如果flags指定了 re.MULTILINE, 每一行都會嘗試去匹配)

“ $ ”  #  匹配字元結尾,若指定flags MULTILINE ,re.search(‘foo.$‘,‘foo1\nfoo2\n‘,re.MULTILINE).group() 會匹配到foo1。 (如果flags指定了 re.MULTILINE, 每一行都會嘗試去匹配)

“ * ”   #  匹配*號前的字元0次或多次, re.search(‘a*‘,‘aaaabac‘)  結果‘aaaa‘; #  ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s.

“ + ”  #  匹配“+”前一個字元1次或多次,re.findall("ab+","ab+cd+abb+bba") 結果[‘ab‘, ‘abb‘]    #  ab+ will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’.

“ ? ”   #  匹配“?”前一個字元1次或0次 ,re.search(‘b?‘,‘alex‘).group() 匹配b 0次    #  ab? will match either ‘a’ or ‘ab’.

“ {m} ”   #  匹配前一個字元m次 ,re.search(‘b{3}‘,‘alexbbbs‘).group()  匹配到‘bbb‘   

“ {n,m} ”   #  匹配前一個字元n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 結果[‘abb‘, ‘ab‘, ‘abb‘]  

“ [ ] ”  #  Used to indicate a set of characters.  在[ ] 中的字元, 可以單獨列出來(如:[abc123]),也可以用“-”表示一個範圍(如:[0-9])

“ | ”  #  匹配|左或|右的字元,re.search("abc|ABC","ABCBabcCD").group() 結果‘ABC‘

“ ( ... ) ”  # 分組匹配; 利用 .groups() 查看分開後的匹配結果(元祖形式)(涉及到分組就用. groups())

註:以上的全部都經常使用

“ \A ”  # 只從字元開頭匹配,re.search("\Aabc","alexabc") 是匹配不到的,相當於re.match(‘abc‘,"alexabc") 或re.search(‘^abc‘, ‘xxx‘)

“ \Z ”  # 匹配字元結尾, 同$ 

“ \d ”   # 匹配數字0到9, 相當於[0-9](經常使用)   #  re.search(‘\d+‘, string)   #  貪婪匹配模式

“ \D ”    #  匹配非數字 (經常使用)

“ \w ”   #   匹配[A-Za-z0-9] (即非特殊字元)  (經常使用)

“ \W ”   #  匹配非[A-Za-z0-9] (即特殊字元) (經常使用)

“ \s ”   #  匹配空白字元、\n、\t、\r ; 

“ (?P<name>...) ”   # 分組匹配 ; 舉例如下:

import reid_s = ‘130704200005251653‘res = re.search(‘(?P<province>\d{3})(?P<city>\d{3})(?P<born_year>\d{4})‘,id_s)print(res.group())print(res.groups())   # 涉及到分組就用 groups# 以字典的形式輸出print(res.groupdict())# 列印結果:# 1307042000# (‘130‘, ‘704‘, ‘2000‘)# {‘province‘: ‘130‘, ‘city‘: ‘704‘, ‘born_year‘: ‘2000‘}

 

re的匹配文法有以下幾種:

  • re.match(pattern,string,flags=0)    #  從頭開始匹配;檢測字串的第一個元素是否匹配你所設定的pattern,後面的元素不再檢測是否匹配,並返回匹配到的元素或者“None”  #  官方解釋:

    If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

    Note that even in MULTILINE mode, re.match() will only match at the beginning of the string and not at the beginning of each line.

    If you want to locate a match anywhere in string, use search() instead

  • re.search(pattern,string,flags=0)    #  遍曆整個字串找到第一個匹配你pattern的元素,後面的元素不再檢測是否匹配,並返回匹配到的元素或者“None”   # 官方解釋: Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.
  • re.findall(pattern, string,flags=0)  #  把所有匹配到的字元(元素)放到以列表中的元素返回   # 官方解釋:  Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right(從左向右掃描字串匹配), and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.

下面看下re.match()和 re.search()的運行效果:

import res = ‘1ab2c3‘print(re.search(‘[0-9]‘,s))print(re.match(‘[0-9]‘,s))#  列印結果:#  <_sre.SRE_Match object; span=(0, 1), match=‘1‘>#  <_sre.SRE_Match object; span=(0, 1), match=‘1‘>   #  search 和match返回的是一個對象, 不是匹配到的值。# 要得到匹配到的值,可以利用 .group(),但需要先判斷是否存在,因為如果沒有匹配到就用.group()程式會報錯res_match = re.search(‘[0-9]‘,s)if res_match:   #  先進行判斷    print(res_match.group())# 列印結果:# 1
  •  re,split(patternstringmaxsplit=0,flags=0)   #  以匹配到的字元作為分隔字元(Regex可以用來做模糊規則)
情況1:import res = ‘neo22alex18#mike-oldboy‘print(re.split(‘\d+|#|-‘,s))   # pattern:按照 \d+ 或者“#” 或者 - 去split#  輸出結果:#  [‘neo‘, ‘alex‘, ‘‘, ‘mike‘, ‘oldboy‘]   # 第3個空元素是因為18split之後 “#”也split, 成了空元素

# 上面是利用管道符“|”去定義pattern,下面利用[]去定義
import re
s = ‘neo22alex18#mike-oldboy‘
print(re.split(‘[\d+#-]‘,s)) # []就表示裡面的都包括,效果就跟“|”類似,但有區別(代碼中要注意[]和|具體用哪種), 這個例子只是想強調“[]就表示裡面的都包括”這個知識點
# 輸出結果:
# [‘neo‘, ‘‘, ‘alex‘, ‘‘, ‘‘, ‘mike‘, ‘oldboy‘] # \d+沒有當做一個整體去split,而是分成了\d和字元“+”去split, 我也還沒想清楚為什麼。。。


情況2:
import re
s = ‘neo22alex18|mike-oldboy‘ #
假如要求以“|”為分隔字元
print(re.split(‘\|‘,s))
# | 也是一個文法, 假如你在pattern不想讓它作為文法、而是作為字元來使用, 就在它前面加一個斜杠“\”

# 輸出結果:
# [‘neo22alex18‘, ‘mike-oldboy‘]

# 如果想把斜杠“\”當做字元而不是文法來使用, 就在這個“\”後面再加3個“\”, 即總共4個“\” (不理解原因,先記住吧)
import re
s = ‘neo22alex18\mike-oldboy‘
print(re.split(‘\\\\‘,s))
# 輸出結果:
# [‘neo22alex18‘, ‘mike-oldboy‘] 

 

  • re.sub(patternreplstringcount=0,flags=0)  # 匹配字元並替換
import res = ‘neo22alex18\mike-oldboy‘print(re.sub(‘\d+‘,‘+‘,s))# 輸出結果:# neo+alex+\mike-oldboy
  • re.fullmatch(patternstring,flags=0)   #  全部匹配: 整個字串匹配
re.fullmatch(‘\[email protected]\w+\.(com|cn|edu)‘,"[email protected]")   #  com|cn|edu  是一組的 , 需要放到一個括弧裡面 

# 輸出結果: # <_sre.SRE_Match object; span=(0, 17), match=‘[email protected]‘>

 

  • re.compile(pattern, flags=0)     #  用於編寫一個匹配規則(pattern) # 如果你這個pattern要用很多次,可以利用compile先把pattern設定好, 以後直接調用就行; 不像 re.match(pattern, string)  這類的語句Python需要每次先對pattern編譯,compile的pattern Python只需要編譯一次以後直接調用就行。如下:
Compile a regular expression pattern into a regular expression object, which can be used for matching using its match(), search() and other methods, described below.The sequenceprog = re.compile(pattern)result = prog.match(string)is equivalent toresult = re.match(pattern, string)but using re.compile() and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program.

Flag標識符:

  • re.I(re.IGNORECASE): 忽略大小寫(括弧內是完整寫法,下同)
  • M(MULTILINE): 多行模式,改變‘^‘和‘$‘的行為
  • S(DOTALL): 改變‘.‘的行為:make the ‘.‘ special character match any character at all, including a newline(換行); without this flag, ‘.‘ will match anything except a newline. (分行符號也包括在內)
  • X(re.VERBOSE) 可以給你的運算式寫注釋,使其更可讀,下面這2個意思一樣

a = re.compile(r"""\d + # the integral part                \. # the decimal point                \d * # some fractional digits""",                 re.X)b = re.compile(r"\d+\.\d*")

 

軟體開發目錄規範:

正常化的目錄結構能更好的控製程序就夠,讓程式具有更高的可讀性。

“項目目錄規範”其實也屬於“可讀性和可維護性”的範疇,設計層次清晰的目錄結構就是為了達到以下兩點:

1. 可讀性高: 不熟悉這個項目代碼的人,一眼就能就能看懂目錄結構,知道程式啟動指令碼是哪個,測試目錄在哪兒,設定檔在哪兒等等,從而非常快速的瞭解這個項目

2. 可維護性高: 定義好組織規則後,維護著就能明確的知道,新增的哪個檔案和代碼應該放在什麼目錄下。這個的好處是,隨著代碼/配置的規模增加,項目結構不會混亂,仍然能組織良好。

通常一個項目都會有的目錄如下:

luffy   # 建議全小寫

    log  # 日誌目錄

 conf/config/settings   # 設定檔目錄

 libs/modules   # 第三方庫目錄

 core/luffy     # 程式碼目錄/核心代碼目錄

 docs    # 文件庫

 README  #  對軟體的說明

 setup.py  #  快速安裝

 bin  #  程式的啟動指令碼/程式的入口

  luffy_server.py

 

README的寫法:

  1. 軟體定位,軟體的準系統。
  2. 運行代碼的方法: 安裝環境、啟動命令等。
  3. 簡要的使用說明。
  4. 代碼目錄結構說明,更詳細點可以說明軟體的基本原理。
  5. 常見問題說明。

關係目錄規範的詳情可參考:  https://www.luffycity.com/python-book/di-4-zhang-python-ji-chu-2014-chang-yong-mo-kuai/ruan-jian-kai-fa-mu-lu-gui-fan.html

 

Python模組:Re模組、附軟體開發目錄規範

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.