11

脚注を作成する Python スクリプトを作成したいと考えています。アイデアは、並べ替えのすべての文字列を見つけて、"Some body text.{^}{Some footnote text.}"それらを に置き換えることです。"Some body text.^#"ここ"^#"で、 は適切な脚注番号です。(私のスクリプトの別の部分では、ファイルの下部にある脚注を実際に出力します。) これに使用している現在のコードは次のとおりです。

pattern = r"\{\^\}\{(.*?)\}"
i = 0
def create_footnote_numbers(match):
   global i
   i += 1
   return "<sup>"+str(i)+"</sup>"

new_body_text = re.sub(pattern, create_footnote_numbers, text)

これは問題なく動作しますが、変数 ( i) を関数の外で宣言してからcreate_footnote_numbers、その関数内で呼び出す必要があるのは奇妙に思えます。re試合の番号を返す何かが内部にあると思っていたでしょう。

4

3 に答える 3

14

任意の callable を使用できるため、クラスを使用して番号付けを追跡できます。

class FootnoteNumbers(object):
    def __init__(self, start=1):
        self.count = start - 1

    def __call__(self, match):
        self.count += 1
        return "<sup>{}</sup>".format(self.count)


new_body_text = re.sub(pattern, FootnoteNumbers(), text)

これで、カウンターの状態がFootnoteNumbers()インスタンスに含まれ、実行self.countを開始するたびに新たに設定されre.sub()ます。

于 2013-05-26T17:12:11.383 に答える