跳转到内容

User:喵/langlinks replace.js

维基百科,自由的百科全书

这是本页的一个历史版本,由留言 | 贡献2012年10月13日 (六) 09:55 建立内容为“// To apply this script on the current article, open the EDIT page of the article, and use this bookmarklet: // javascript:importScriptURI("https://...”的新頁面)编辑。这可能和当前版本存在着巨大的差异。

(差异) ←上一修订 | 最后版本 (差异) | 下一修订→ (差异)
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google ChromeFirefoxMicrosoft EdgeSafari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
// To apply this script on the current article, open the EDIT page of the article, and use this bookmarklet:
// javascript:importScriptURI("https://zh.wikipedia.org/w/index.php?title=User:%E5%96%B5/langlinks_replace.js&action=raw");
// After quries, the wikilinks in the editbox will be replaced by its corresponding article in ZHWP.
// Please do NOT save the replaced article. Instead, copy the content to ZHWP.
// <nowiki>
(function (mw, $) {
  var api = new mw.Api();
  var wlregex = /\[\[([^:|\]]+)(\|[^\]]*)?\]\]/g;
  var map = {};
  var requests = [];
  var current = 0;
  var textbox = $('#wpTextbox1');
  var wikitext = textbox.val();
  if (textbox.length == 0) {
    alert('This script must be run on the EDIT page.');
  }
  var query_complete = function (data) {
    var pages = data["query"]["pages"];
    for (var p in pages)
    {
      var ll = pages[p]["langlinks"];
      for (var i in ll) {
        if (ll[i]["lang"] == "zh") {
          map[pages[p]["title"]] = ll[i]["*"];
        }
      }
    }
    var norm = data["query"]["normalized"];
    if (norm) {
      for (var i in norm) {
        map[norm[i]["from"]] = map[norm[i]["to"]];
      }
    }
    if (data["query-continue"]) {
      api.get({
        action:'query',
        titles: requests[current].join('|'),
        prop:'langlinks',
        lllimit:'500',
        llcontinue: data["query-continue"]["langlinks"]["llcontinue"]
      }).done(query_complete)
    } else {
      current++;
      if (current >= requests.length) {
        var result = wikitext.replace(
          wlregex,
          function (s) {
            var q = /\[\[([^:|\]]+)(\|[^\]]*)?\]\]/g.exec(s);
            var re = map[q[1]];
            if (!re) return s;
            return s.replace(q[1], re);
          }
        );
        console.log(map);
        $('#wpTextbox1').val(result);
        alert("Done!");
      } else {
        query(requests[current]);
      }
    }
  };

  var query = function (articles) {
    api.get({
      action:'query',
      titles: articles.join('|'),
      prop:'langlinks',
      lllimit:'500'
    }).done( query_complete )
  };

  var match = wlregex.exec(wikitext);
  var t = [];
  while (match != null) {
    if (t.length == 50) {
      requests.push(t);
      t = [];
    } else {
      t.push(match[1]);
    }
    match = wlregex.exec(wikitext);
  }
  if (t.length > 0) {
    requests.push(t);
  }
  query(requests[current]);
})(mediaWiki, jQuery);
// </nowiki>