一些問題,我希望做一些文字轉換,例如從文本文件閱讀:有關正則表達式在Python
CONTENTS
1. INTRODUCTION
1.1 The Linear Programming Problem 2
1.2 Examples of Linear Problems 7
,並寫入到另一個文本文件:
("CONTENTS" "#")
("1. INTRODUCTION" "#")
("1.1 The Linear Programming Problem 2" "#11")
("1.2 Examples of Linear Problems 7" "#16")
目前我用這種轉換Python代碼是:
infile = open(infilename)
outfile = open(outfilename, "w")
pat = re.compile('^(.+?(\d+)) *$',re.M)
def zaa(mat):
return '("%s" "#%s")' % (mat.group(1),str(int(mat.group(2))+9))
outfile.write('(bookmarks \n')
for line in infile:
outfile.write(pat.sub(zaa,line))
outfile.write(')')
它將原來的文本轉換爲
CONTENTS 1. INTRODUCTION ("1.1 The Linear Programming Problem 2" "#11") ("1.2 Examples of Linear Problems 7" "#16")
最後兩行是正確的,但 前兩行不。所以我 想知道如何通過修改 當前代碼或使用一些 不同的代碼來容納前兩行: ?
該代碼不是我自己寫的,但是 我想了解
re.sub()
這裏的用法 。當我從 一個Python網站,re.sub(regex, replacement, subject) performs a search-and-replace across subject, replacing all matches of regex in subject with replacement. The result is returned by the sub() function. The subject string you pass is not modified.
但在我的代碼中發現,它的用法是 `pat.sub(ZAA,線)」,這似乎 我不帶引號的 描述一致。所以我想知道如何 瞭解我的代碼中的用法?
謝謝!
這是真正的代碼?你正在添加11,但2 + 11 = 13不是11. – Mikel 2011-04-03 02:55:09
@Mikel:謝謝你指出。我的錯字。剛剛糾正。 – Tim 2011-04-03 02:56:15
我也對're.sub()'的東西感到困惑。原來有_two_子函數:'re.sub(pattern,repl,string [,count])',另一個用於編譯正則表達式對象:'RegexObject.sub(repl,string [,count = 0]) '。該函數使用後一種語法。 – ridgerunner 2011-04-03 03:17:28