计算从维基百科 api 返回的 json 文件中的单词出现次数
Count word occurrence in the json file returned from wikipedia api
我正在尝试计算从维基百科 api 返回的 json 文件中某个词的出现次数 api。
比如我想统计json文件中apple出现的次数
https://en.wikipedia.org/w/api.php?action=parse§ion=0&prop=text&format=json&page=apple
我有一些代码,但没有用。
var wikiURL = "https://en.wikipedia.org/w/api.php?action=parse§ion=0&prop=text&format=json&page=apple"
$.ajax({
// ajax settings
url: wikiURL,
method: "GET",
dataType: "jsonp",
}).done(function (data) {
// successful
var temp =data.parse.text;
console.log(temp);
// temp is an object, how to count word apple from it?
}).fail(function () {
// error handling
alert("failed");
});
你可以这样做:
var wikiURL = "https://en.wikipedia.org/w/api.php?action=parse§ion=0&prop=text&format=json&page=apple"
$.ajax({
// ajax settings
url: wikiURL,
method: "GET",
dataType: "jsonp",
}).done(function (data) {
// successful
var temp = data.parse.text['*'];
const regex = /(apple)+/gmi; //g - globally, m - multi line, i - case insensitive
let m;
let cnt = 0;
while ((m = regex.exec(temp)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
cnt++;
// The result can be accessed through the `m`-variable.
/*m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});*/
}
console.log(cnt); //
}).fail(function () {
// error handling
alert("failed");
});
您可以在此处查看正在运行的正则表达式:https://regex101.com/r/v9Uoh6/1
我正在尝试计算从维基百科 api 返回的 json 文件中某个词的出现次数 api。
比如我想统计json文件中apple出现的次数
https://en.wikipedia.org/w/api.php?action=parse§ion=0&prop=text&format=json&page=apple
我有一些代码,但没有用。
var wikiURL = "https://en.wikipedia.org/w/api.php?action=parse§ion=0&prop=text&format=json&page=apple"
$.ajax({
// ajax settings
url: wikiURL,
method: "GET",
dataType: "jsonp",
}).done(function (data) {
// successful
var temp =data.parse.text;
console.log(temp);
// temp is an object, how to count word apple from it?
}).fail(function () {
// error handling
alert("failed");
});
你可以这样做:
var wikiURL = "https://en.wikipedia.org/w/api.php?action=parse§ion=0&prop=text&format=json&page=apple"
$.ajax({
// ajax settings
url: wikiURL,
method: "GET",
dataType: "jsonp",
}).done(function (data) {
// successful
var temp = data.parse.text['*'];
const regex = /(apple)+/gmi; //g - globally, m - multi line, i - case insensitive
let m;
let cnt = 0;
while ((m = regex.exec(temp)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
cnt++;
// The result can be accessed through the `m`-variable.
/*m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});*/
}
console.log(cnt); //
}).fail(function () {
// error handling
alert("failed");
});
您可以在此处查看正在运行的正则表达式:https://regex101.com/r/v9Uoh6/1