Python3でre.sub()を使った正規表現による置換に関して質問です。
例えばa = 'aaa, bbb[12, 13, 14]. ccc.'
といった文字列の角かっこに囲まれた数字を'[12] [13] [14]'
のようにそれぞれを角かっこで囲うように変換したいです。
追記
すみません。例が不適切でした。
今回の質問は論文の引用表記を置換したいというものでした。
http://journals.plos.org/plosmedicine/article?id=10.1371/journal.pmed.0030232
問題は単純にカンマを角かっこに置換するだけではないという点です。
文章中に含まれている他のカンマは置き換えたくないです。
つまり、第一引数は以下のようになるかと思います。
re.sub('[(\d+, )+(\d+)]', '', a)
この条件で合致したときだけ', 'を'] ['に変換したいのですが、後方参照をどのように利用すればいいのかわかりません。
re.sub('[(\d+, )+(\d+)]', r'[\1] [\2]', a)
としたところ'[13, ] [15]'
となってしまいました。
アドバイスをいただけたら幸いです。
*追記
正規表現を使わない方法については以下のような方法で解決できました。
引数はa.strip()です。
def get_refer(words): start = 0 dic = [] for tmp in words: if re.match('[\d+]', tmp): dic.append(tmp) continue if re.match('[\d+(-|–)\d+]', tmp): dic.append(tmp) continue if re.match('[\d', tmp): start = 1 num = tmp.strip('[').strip(',') fin = '['+num+']' # print(fin) dic.append(fin) continue # if re.match('(\d+-)?\d+]', tmp): if re.match('.*\d+]', tmp): start = 0 num = tmp.strip(']') fin = '['+num+']' # print(fin) dic.append(fin) continue if start == 1: tmp = tmp.strip(',') fin = '['+tmp+']' # print(fin) dic.append(fin) else: dic.append(tmp) return dic
回答4件
あなたの回答
tips
プレビュー