2012-04-18 20 views
0

這是我昨天問的question。我能夠獲得所需的數據。最終的數據是這樣的。請按照這個linkwikimedia api獲取json字符串的相關數據

我用下面的代碼試圖讓所有的信息框數據

       content = content.split("}}\n"); 
           for(k in content) 
           { 
            if(content[k].search("Infobox")==2) 
            { 
             var infobox = content[k]; 
             alert(infobox); 
             infobox = infobox.replace("{{",""); 
             alert(infobox); 
             infobox = infobox.split("\n|"); 
             //alert(infobox[0]); 
             var infohtml=""; 
             for(l in infobox) 
             { 
              if(infobox[l].search("=")>0) 
              { 
               var line = infobox[l].split("="); 

               infohtml = infohtml+"<tr><td>"+line[0]+"</td><td>"+line[1]+"</td></tr>"; 

              } 
             } 
             infohtml="<table>"+infohtml+"</table>"; 
             $('#con').html(infohtml); 
             break; 
            } 
           } 

我最初以爲每個元素包含在{{}}。所以我寫了這段代碼。但是我看到的是,我無法用這個獲得整個信息框數據。有這個元素

{{Sfn|National Informatics Centre|2005}} 

發生這結束我的信息框數據。

不使用json似乎更簡單。請幫我

+0

解析Wikitext比解析HTML更邪惡:-) – Bergi 2012-04-18 16:37:18

回答

1

你試過DBpedia? Afaik他們提供模板使用信息。還有一個名爲Templatetiger的工具服務器工具,它可以從靜態轉儲(不生存)中進行模板提取。

然而,我曾經寫過一個小片段來提取wikitext的模板在javascript:

var title; // of the template 
var wikitext; // of the page 
var templateRegexp = new RegExp("{{\\s*"+(title.indexOf(":")>-1?"(?:Vorlage:|Template:)?"+title:title)+"([^[\\]{}]*(?:{{[^{}]*}}|\\[?\\[[^[\\]]*\\]?\\])?[^[\\]{}]*)+}}", "g"); 
var paramRegexp = /\s*\|[^{}|]*?((?:{{[^{}]*}}|\[?\[[^[\]]*\]?\])?[^[\]{}|]*)*/g; 
wikitext.replace(templateRegexp, function(template){ 
    // logabout(template, "input "); 
    var parameters = template.match(paramRegexp); 
    if (!parameters) { 
     console.log(page.title + " ohne Parameter:\n" + template); 
     parameters = []; 
     } 
    var unnamed = 1; 
    var p = parameters.reduce(function(map, line) { 
     line = line.replace(/^\s*\|/,""); 
     var i = line.indexOf("="); 
     map[line.substr(0,i).trim() || unnamed++] = line.substr(i+1).trim(); 
     return map; 
    }, {}); 
    // you have an object "p" in here containing the template parameters 
}); 

,設有一個級別的嵌套模板,但還是很容易出錯。使用正則表達式解析wikitext與嘗試在html上執行操作一樣邪惡:-)

查詢parse-tree from the apiapi.php?action=query&prop=revisions&rvprop=content&rvgeneratexml=1&titles=...可能更容易。 從該分析樹中,您將能夠輕鬆地提取模板。