文字列から数字を検索しようとしていますが、それらを見つけると、文字をいくつかの文字で囲みます。
a = "hello, i am 8 years old and have 12 toys"
a = method(a)
print a
"hello, i am \ref{8} years old and have \ref{12} toys"
re (正規表現) ライブラリを見てきましたが、役立つものが見つからないようです...クールなアイデアはありますか?
これは、メソッドの非常に基本的な使用.sub
法です。
numbers = re.compile(r'(\d+)')
a = numbers.sub(r'\ref{\1}', a)
\d+
数字パターンを囲む括弧はグループを作成し、参照\1
はグループの内容に置き換えられます。
>>> import re
>>> a = "hello, i am 8 years old and have 12 toys"
>>> numbers = re.compile(r'(\d+)')
>>> a = numbers.sub(r'\\ref{\1}', a)
>>> print a
hello, i am \ref{8} years old and have \ref{12} toys
これらの行に沿って re.sub 関数を使用する必要があります:
re.sub("(\d+)",my_sub_func,text)
# ここで数値をキャッチします (ただし、非実数のみをキャッチします)。 my_sub_func は次のように定義されています。
def my_sub_func(match_obj):
text = match_obj.group(0) # get the digit text here
new_text = "\\ref{"+text+"}" # change the pattern here
return new_text`