我想插入一些導入行到python源文件中,但我理想情況下將它們放在最初的文檔字符串之後。假設我將文件加載到行變量中,如下所示:如何跳過使用正則表達式的文檔字符串
lines = open('filename.py').readlines()
如何查找行號,其中文檔字符串結束?
我想插入一些導入行到python源文件中,但我理想情況下將它們放在最初的文檔字符串之後。假設我將文件加載到行變量中,如下所示:如何跳過使用正則表達式的文檔字符串
lines = open('filename.py').readlines()
如何查找行號,其中文檔字符串結束?
如果您使用的是標準的文檔字符串格式,你可以做這樣的事情:
count = 0
for line in lines:
if line.startswith ('"""'):
count += 1
if count < 3:
# Before or during end of the docstring
continue
# Line is after docstring
可能需要一些適應的,沒有文檔字符串的文件,但如果你的文件格式一致,應該是很容易。
而不是使用正則表達式,或依靠特定的格式,你可以使用python的tokenize模塊。
import tokenize
f=open(filename)
insert_index = None
for tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline):
if tok == tokenize.COMMENT:
continue
elif tok == tokenize.STRING:
insert_index = erow, ecol
break
else:
break # No docstring found
這種方式,您甚至可以處理病理情況下,如:
# Comment
# """Not the real docstring"""
' this is the module\'s \
docstring, containing:\
""" and having code on the same line following it:'; this_is_code=42
excactly如蟒蛇會處理它們。
這是一個基於Brian的精彩回答一個功能,您可以使用一個文件分割成文檔字符串和代碼:
def split_docstring_and_code(infile):
import tokenize
insert_index = None
f = open(infile)
for tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline):
if tok == tokenize.COMMENT:
continue
elif tok == tokenize.STRING:
insert_index = erow, ecol
break
else:
break # No docstring found
lines = open(infile).readlines()
if insert_index is not None:
erow = insert_index[0]
return "".join(lines[:erow]), "".join(lines[erow:])
else:
return "", "".join(lines)
它會假設結束文檔字符串的行不包含額外的代碼過去的結束分隔符的字符串。
請注意,PEP8建議在docstrings之前放置導入。 – 2008-10-01 07:47:46
不,PEP8不建議這樣做,它實際上會使文檔不是docstrings。當它們是模塊,類或函數中的第一個表達式時,Docstrings只是docstrings。 PEP8表示,進口必須在評論和文件串後立即生效。 – 2008-10-01 08:29:25