在Python中查找和替換文本

最簡單的查找替換

在Python中查找和替換很是簡單,若是當前對象是一個字符串str時,你可使用該類型提供的find()或者index()方法查找指定的字符,若是能找到則會返回字符第一次出現的索引,若是不存在則返回-1。html

>>> s = 'Cat and Dog'
>>> s.find('Dog')
8
>>> s.index('Dog')
8
>>> s.find('Duck')
-1

若是要替換目標字符串,用replace()方法就行了。python

>>> s = 'Cat and Dog'
>>> s.replace('Cat', 'Dog')
'Dog and Dog'

通配符查找匹配

固然,若是你以爲上面的功能還不能知足你,你想使用通配符來查找字符串?沒問題!fnmatch這個庫就能知足你的要求,看例子!正則表達式

>>> s = 'Cat and Dog'
>>> import fnmatch
>>> fnmatch.fnmatch(s,'Cat*')
True
>>> fnmatch.fnmatch(s,'C*and*D?')
False
>>> fnmatch.fnmatch(s,'C*and*D*')
True

正則表達式查找替換

若是你須要查找比較複雜的字符規則,正則表達式是你不二的選擇。下面是正則查找的簡單示例。api

>>> import re
>>> s = 'We will fly to Thailand on 2016/10/31'
>>> pattern = r'\d+'
>>> re.findall(pattern, s)
['2016', '10', '31']
>>> re.search(pattern, s)
<_sre.SRE_Match object at 0x03A8FD40>
>>> re.search(pattern, s).group()
'2016'

接下來你可能須要用正則表達式去替換某些字符,那麼你須要瞭解re.sub()方法,看例子。閉包

>>> s = "I like {color} car."
>>> re.sub(r'\{color\}','blue',s)
'I like blue car.'

>>> s = 'We will fly to Thailand on 10/31/2016'
>>> re.sub('(\d+)/(\d+)/(\d+)', r'\3-\1-\2', s)
'We will fly to Thailand on 2016-10-31'

其實re.sub()遠比你相像的強大的多。在上面的例子裏你能夠替換相似於{color}這樣的模板字符,也能夠把正則匹配到的全部分組調換順序,例如第二個例子一共匹配了3個分組,而後把第3個分組放到最前面 r'3-1-2',看明白了嗎?函數

接下來看另一個例子。測試

s = "Tom is talking to Jerry."
name1 = "Tom"
name2 = "Jerry"

pattern = r'(.*)({0})(.*)({1})(.*)'.format(name1, name2)
print re.sub(pattern, r'\1\4\3\2\5', s)
# Jerry is talking to Tom.

其實你還能夠自定義替換函數,也就是re.sub()的第二個參數。spa

def change_date(m):
    from calendar import month_abbr
    mon_name = month_abbr[int(m.group(1))]
    return '{} {} {}'.format(m.group(2), mon_name, m.group(3))

s = 'We will fly to Thailand on 10/31/2016'
pattern = r'(\d+)/(\d+)/(\d+)'
print re.sub(pattern, change_date, s)
# We will fly to Thailand on 31 Oct 2016

最後給你們一個終極版的例子,裏面用到了函數的閉包,着酸爽,你懂的!code

def match_case(word):
    def replace(m):
        text = m.group()
        if text.isupper():
            return word.upper()
        elif text.islower():
            return word.lower()
        elif text[0].isupper():
            return word.capitalize()
        else:
            return word
    return replace

s = "LOVE PYTHON, love python, Love Python"
print re.sub('python', match_case('money'), s, flags=re.IGNORECASE)
# LOVE MONEY, love money, Love Money

寫在最後

其實正則表達式還有不少玩法,若是你想讓正則和通配符混合着用,一點問題都沒有,由於fnmatch還有一個translate()的方法,可讓你把通配符無痛轉換成正則表達式,你愛怎麼玩就怎麼玩。orm

>>> fnmatch.translate('C*and*D*')
'C.*and.*D.*'

關於做者:Python技術愛好者,目前從事測試開發相關工做,轉載請註明原文出處。

歡迎關注個人博客 http://betacat.online,你能夠到個人公衆號中去當吃瓜羣衆。

Betacat.online

相關文章
相關標籤/搜索