0

XML ダンプから Wiki テキストを解析しています。'section' という名前の文字列には、再編成したいいくつかの引数を含む、二重中かっこで囲まれたテンプレートが含まれています。

これには、TextTerm という名前の例があります。

section="Sample of a text with a first template {{TextTerm|arg1a|arg2a|arg3a...}}  and then a second {{TextTerm|arg1b|arg2b|arg3b...}} etc."

正規表現を使用scanして各テンプレートを取得し、次を使用してループで作業できます。

section.scan(/\{\{(TextTerm)\|(.*?)\|(.*?)\}\}/i).each { |item| puts "1=" + item[1] # arg1a etc.}

そして、テンプレートの第一引数のデータベースを抽出できました。

次に、テンプレート「NewTextTerm」の名前を置き換え、最初の引数の代わりに 2 番目の引数を配置して引数を再編成します。

同じループでそれを行うことはできますか? たとえば、次のように変更scanしますgsub(rgexp){ block}

section.gsub!(/\{\{(TextTerm)\|(.*?)\|(.*?)\}\}/) { |item| '{{NewTextTerm|\2|\1}}'}

私は得る:

"Sample of a text with a first template {{NewTextTerm|\\2|\\1}}  and then a second {{NewTextTerm|\\2|\\1}} etc."

正規表現の引数が認識されないことを意味します。gsub機能したとしても、ブロック内に引数を処理する場所が必要です。たとえばputsgsubブロックに似たブロックを使用することはできませんが、scan().each置換する文字列のみを使用できます。

どんなアイデアでも大歓迎です。

PS: 一部の編集: 中括弧と「section= が追加されました」、コードが完成しました。

4

2 に答える 2

0

はい、二重引用符で引用符を変更するだけでは不十分です。#$1 が答えです。完全なコードは次のとおりです。

section="Sample of a text with a first template {{TextTerm|arg1a|arg2a|arg3a...}}  and then a second {{TextTerm|arg1b|arg2b|arg3b...}} etc."
section.gsub(/\{\{(TextTerm)\|(.*?)\|(.*?)\}\}/) { |item| "{{New#$1|#$3|#$2}}"}
"Sample of a text with a first template {{NewTextTerm|arg2a|arg3a...|arg1a}}  and then a second {{NewTextTerm|arg2b|arg3b...|arg1b}} etc."

したがって、それは機能します。ありがとう。

しかし今、変更された文字列を返す「関数」で文字列を置き換える必要があります。

def stringreturn(arg1,arg2,arg3) strr = "{{New"+arg1 + arg3 +arg2 + "}}"; return strr ; end

section.gsub(/\{\{(TextTerm)\|(.*?)\|(.*?)\}\}/) { |item| stringreturn("#$1","|#$2","|#$3") }

戻ります:

"Sample of a text with a first template {{NewTextTerm|arg2a|arg3a...|arg1a}}  and then a second {{NewTextTerm|arg2b|arg3b...|arg1b}} etc."

ありがとうございます!Ruby を使用して MediaWiki テンプレートの引数を操作するには、おそらくもっと良い方法があります。

于 2013-09-09T08:36:03.653 に答える