我正在尝试计算Wikipedia api返回的json文件中一个单词的出现。
例如,我想计算json文件中苹果的出现。
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");
});
答案 0 :(得分:1)
您可以这样做:
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