2015年12月25日 星期五

[ Python 常見問題 ] 如何用 Python 來進行查詢和替換一個文本字符串?

Source From Here
可以使用 sub() 方法來進行查詢和替換,sub 方法的格式為:
re.sub(patternreplstringcount=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \j are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern. For example:
>>> import re
>>> re.sub(r'(blue|white|red)', 'colour', 'blue socks and red shoes')
'colour socks and colour shoes'

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example:
>>> def colorRepl(matchObj):
... if matchObj.group(0) == 'blue': return 'bluest'
... elif matchObj.group(0) == 'red': return 'redest'
... else: return 'colour'
...
>>> re.sub(r'(blue|white|red)', colorRepl, 'blue sock, red shoes, white cloth and orange cap')
'bluest sock, redest shoes, colour cloth and orange cap'

subn() 方法執行的效果跟 sub() 一樣,不過它會返回一個二維數組,包括替換後的新的字符串和總共替換的數量:
re.subn(pattern, repl, string, count=0, flags=0)
Perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made). For example:
>>> re.subn(r'(blue|white|red)', 'colour', 'blue socks and red shoes')
('colour socks and colour shoes', 2)
>>> re.subn(r'(blue|white|red)', 'colour', 'blue socks and red shoes', count=1)
('colour socks and red shoes', 1)


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...