2010-03-19 69 views
6

我已經寫了epytextreST標記轉換器,現在我想將我的整個庫中的所有文檔字符串從epytext轉換爲reST格式。替換python docstrings

是否有智能的方式來讀取模塊中的所有文檔並寫回替換?

ps:ast模塊或許?

回答

0

也許最簡單的做法就是用老式的方式做。這裏有一些最初的代碼讓你去。這也許可能是更漂亮,但應該瞭解基本的概念:

def is_docstr_bound(line): 
    return "'''" in line or '"""' in line 

# XXX: output using the same name to some other folder 
output = open('output.py', 'w') 

docstr_found = False 
docstr = list() 
with open('input.py') as f: 
    for line in f.readlines(): 
     if docstr_found: 
      if is_docstr_bound(line): 
       # XXX: do conversion now 
       # ... 

       # and write to output 
       output.write(''.join(docstr)) 

       output.write(line) 

       docstr = list() 
       docstr_found = False 
      else: 
       docstr.append(line) 
     else: 
      if is_docstr_bound(line): 
       docstr_found = True 

      output.write(line) 

output.close() 

,使之真正功能,你需要有一個文件搜索器和輸出文件把它掛到其他目錄。查看os.path模塊以供參考。

我知道文檔字符串綁定檢查可能真的很弱。這可能是一個好主意(帶狀線,並檢查它是否以文檔字符串綁定開始或結束)。

希望能給出一些想法如何繼續下去。也許有更好的方法來處理這個問題。 :)

+0

散步槽我的目錄結構和開/讀/寫文件,實在是微不足道。 我的問題是:是否有一種聰明的方式來讀取模塊中的所有文檔並寫回替代品? 這不能用像正則表達式這樣的機制(像re.finditer('\「\」\「(。*)\」\「\」',source))那樣天真地做,因爲我不想搞亂剩下的代碼。 – tomaz 2010-03-19 17:23:32

+2

我發現了一個類似的問題,您可能會感興趣。請參閱http://stackoverflow.com/questions/768634/python-parse-a-py-file-read-the-ast-modify-it-then-write-back-the-modified。 – 2010-03-19 17:34:18

+1

Docstrings不需要有三重引號的字符串,並且不是所有用三引號字符串引用的都是一個文檔字符串,所以這隻適用於python文檔字符串的一個子集。 – jcdyer 2010-03-19 19:17:00

0

我想知道內省和源處理的組合。下面是一些未經測試的僞代碼:

import foo #where foo is your module 

with open('foo.py',r) as f: 
    src = f.readlines() 

for pything in dir(foo): #probably better ways to do this... 
    try: 
     docstring = pything.__doc__ 
    except AttributeError: 
     #no docstring here 
     pass 

    #modify the docstring 
    new_docstring = my_format_changer(docstring) 

    #now replace it in the source 
    src = src.replace(docstring, new_docstring) 

#When done, write it out 
with open('new_foo.py','w') as fout: 
    fout.write(src) 

顯然你必須把一些小聰明在橫穿模塊查找具有文檔字符串因此將遞歸對象的代碼,但是這給你的總體思路。

2

這可能是一個矯枉過正的簡單用法,但我會考慮使用2to3進行編輯。你只需要編寫一個自定義修復程序。這不是很好的記載,但開發人員指南到Python 3.0:Python的2.6和遷移2到3:More about 2to3Implement Custom Fixers給予足夠的細節,上手...

epydoc的似乎包含一個to_rst()方法可能有助於你實際上翻譯了文檔字符串。不知道它是否有什麼好...

4

Pyment是一個工具,可以轉換Python docstrings和創建缺少的骨架。它可以管理谷歌epydoc的(javadoc的風格),NumpydocreStructuredText的(休息,獅身人面像默認值)文檔字符串格式。

它接受單個文件或文件夾(也瀏覽子文件夾)。對於每個文件,它將識別每個文檔字符串格式並將其轉換爲所需的格式。最後,將生成一個補丁以應用於該文件。

要轉換的項目:

  • 安裝Pyment

鍵入以下內容(可以使用的virtualenv):

$ git clone https://github.com/dadadel/pyment.git 
$ cd pyment 
$ python setup.py install 
  • 從epydoc的皈依獅身人面像

您可以通過執行轉換您的項目,獅身人面像格式(REST),這是默認的輸出格式,:

$ pyment /my/folder/project