NLP 基礎

1. re模塊

  • 1.將正則表達式的字符串形式編譯爲Pattern實例
  • 2.使用Pattern實例處理文本並獲得匹配結果(一個Match實例)
  • 3.使用Match實例獲得信息,進行其他的操作。
    import re 
    # 將正則表達式編譯成Pattern對象
    pattern = re.compile(r'hello.*\!')
    # 使用Pattern匹配文本,獲得匹配結果,無法匹配時將返回None
    match = pattern.match('hello! How are you?') 
    if match:
        # 使用Match獲得分組信息
        print(match.group())

    re.compile(strPattern[, flag]):

    flag可選值有:

  • re.I(re.IGNORECASE): 忽略大小寫(括號內是完整寫法,下同)
  • re.M(MULTILINE): 多行模式,改變'^'和'$'的行爲(參見上圖)
  • re.S(DOTALL): 點任意匹配模式,改變'.'的行爲
  • re.L(LOCALE): 使預定字符類 \w \W \b \B \s \S 取決於當前區域設定
  • re.U(UNICODE): 使預定字符類 \w \W \b \B \s \S \d \D 取決於unicode定義的字符屬性
  • re.X(VERBOSE): 詳細模式。這個模式下正則表達式可以是多行,忽略空白字符,並可以加入註釋。以下兩個正則表達式是等價的:
regex_1 = re.compile(r"""\d +  # 數字部分
                         \.    # 小數點部分
                         \d *  # 小數的數字部分""", re.X)
regex_2 = re.compile(r"\d+\.\d*")

 

---match

match屬性:

  • string: 匹配時使用的文本。
  • re: 匹配時使用的Pattern對象。
  • pos: 文本中正則表達式開始搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。
  • endpos: 文本中正則表達式結束搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。
  • lastindex: 最後一個被捕獲的分組在文本中的索引。如果沒有被捕獲的分組,將爲None。
  • lastgroup: 最後一個被捕獲的分組的別名。如果這個分組沒有別名或者沒有被捕獲的分組,將爲None。

方法:

  • group([group1, …]):
    獲得一個或多個分組截獲的字符串;指定多個參數時將以元組形式返回。group1可以使用編號也可以使用別名;編號0代表整個匹配的子串;不填寫參數時,返回group(0);沒有截獲字符串的組返回None;截獲了多次的組返回最後一次截獲的子串。
  • groups([default]):
    以元組形式返回全部分組截獲的字符串。相當於調用group(1,2,…last)。default表示沒有截獲字符串的組以這個值替代,默認爲None。
  • groupdict([default]):
    返回以有別名的組的別名爲鍵、以該組截獲的子串爲值的字典,沒有別名的組不包含在內。default含義同上。
  • start([group]):
    返回指定的組截獲的子串在string中的起始索引(子串第一個字符的索引)。group默認值爲0。
  • end([group]):
    返回指定的組截獲的子串在string中的結束索引(子串最後一個字符的索引+1)。group默認值爲0。
  • span([group]):
    返回(start(group), end(group))。
  • expand(template):
    將匹配到的分組代入template中然後返回。template中可以使用\id或\g、\g引用分組,但不能使用編號0。\id與\g是等價的;但\10將被認爲是第10個分組,如果你想表達\1之後是字符'0',只能使用\g<1>0。
import re
m = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello hanxiaoyang!')
 
print("m.string:", m.string)
print("m.re:", m.re)
print("m.pos:", m.pos)
print("m.endpos:", m.endpos)
print("m.lastindex:", m.lastindex)
print("m.lastgroup:", m.lastgroup)
 
print("m.group(1,2):", m.group(1, 2))
print("m.groups():", m.groups())
print("m.groupdict():", m.groupdict())
print("m.start(2):", m.start(2))
print("m.end(2):", m.end(2))
print("m.span(2):", m.span(2))
print(r"m.expand(r'\2 \1\3'):", m.expand(r'\2 \1\3'))

---Pattern

Pattern對象是一個編譯好的正則表達式,通過Pattern提供的一系列方法可以對文本進行匹配查找。

Pattern不能直接實例化,必須使用re.compile()進行構造。

Pattern提供了幾個可讀屬性用於獲取表達式的相關信息:

  • pattern: 編譯時用的表達式字符串。
  • flags: 編譯時用的匹配模式。數字形式。
  • groups: 表達式中分組的數量。
  • groupindex: 以表達式中有別名的組的別名爲鍵、以該組對應的編號爲值的字典,沒有別名的組不包含在內。
import re
p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL)
 
print("p.pattern:", p.pattern)
print("p.flags:", p.flags)
print("p.groups:", p.groups)
print("p.groupindex:", p.groupindex)

使用pattern

  • match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]):
    這個方法將從string的pos下標處起嘗試匹配pattern:
    • 如果pattern結束時仍可匹配,則返回一個Match對象
    • 如果匹配過程中pattern無法匹配,或者匹配未結束就已到達endpos,則返回None。
    • pos和endpos的默認值分別爲0和len(string)。
      *注意:這個方法並不是完全匹配。當pattern結束時若string還有剩餘字符,仍然視爲成功。想要完全匹配,可以在表達式末尾加上邊界匹配符'$'。 *
  • search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]):
    這個方法從string的pos下標處起嘗試匹配pattern
    • 如果pattern結束時仍可匹配,則返回一個Match對象
    • 若無法匹配,則將pos加1後重新嘗試匹配,直到pos=endpos時仍無法匹配則返回None。
    • pos和endpos的默認值分別爲0和len(string))
import re 
# 將正則表達式編譯成Pattern對象 
pattern = re.compile(r'H.*g') 
# 使用search()查找匹配的子串,不存在能匹配的子串時將返回None 
# 這個例子中使用match()無法成功匹配 
match = pattern.search('hello Hayang!')  
if match: 
    # 使用Match獲得分組信息 
    print(match.group())

# Hayang

split

p = re.compile(r'\d+')
print(p.split('one1two2three3four4'))
# ['one', 'two', 'three', 'four', '']

findall

p = re.compile(r'\d+')
print(p.findall('one1two2three3four4'))
#['1', '2', '3', '4']

finditer

p = re.compile(r'\d+')
for m in p.finditer('one1two2three3four4'):
    print(m.group())
#1
#2
#3
#4

sub

p = re.compile(r'(\w+) (\w+)')
s = 'i say, hello hanxiaoyang!'
 
print(p.sub(r'\2 \1', s))
 
def func(m):
    return m.group(1).title() + ' ' + m.group(2).title()
 
print(p.sub(func, s))

##'say i, hanxiaoyang hello!'
##'I Say, Hello Hanxiaoyang!'

subn

p = re.compile(r'(\w+) (\w+)')
s = 'i say, hello hanxiaoyang!'
 
print(p.subn(r'\2 \1', s))
 
def func(m):
    return m.group(1).title() + ' ' + m.group(2).title()
 
print(p.subn(func, s))
#('say i, hanxiaoyang hello!', 2)
#('I Say, Hello Hanxiaoyang!', 2)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章