我想做一些文本转换,比如从文本文件中读入:
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,line)',这似乎 我与引用的不一致 描述。所以我想知道如何 了解我的代码中的用法?
谢谢!
请您参考如下方法:
使用您的正则表达式,您正在搜索以数字结尾的行(可能还有尾随空格)。您可以将数字设为可选:^(.+?(\d+)?) *$ 并确保 zaa 中的第 2 组引用可以处理空字符串。
def zaa(mat):
return '("%s" "#%s")' % (mat.group(1), (str(int(mat.group(2))+9) if mat.group(2) else "") )
有了这个,当 mat.group(2) 为空时,你应该得到“#”,当它不为空时,你当前得到的是什么。
