Modul:FindWikidataItem4
A modult a Modul:FindWikidataItem4/doc lapon tudod dokumentálni
local p = {}
-- Function to encode URL
local function urlEncode(str)
if str then
str = string.gsub(str, "\n", "\r\n")
str = string.gsub(str, "([^%w ])",
function(c) return string.format("%%%02X", string.byte(c)) end)
str = string.gsub(str, " ", "+")
end
return str
end
-- Function to parse JSON response
local function parseJson(jsonString)
local success, jsonData = pcall(function() return mw.text.jsonDecode(jsonString) end)
if success then
return jsonData
else
return nil
end
end
-- Function to fetch Wikidata item based on Wiktionary page name
local function getWikidataItem(pageName)
local apiUrl = "https://www.wikidata.org/w/api.php"
local action = "wbsearchentities"
local format = "json"
local language = "en"
local searchUrl = apiUrl .. "?action=" .. action .. "&format=" .. format .. "&search=" .. urlEncode(pageName) .. "&language=" .. language
local responseData = mw.http.get(searchUrl)
if responseData and responseData.success then
local decodedData = parseJson(responseData.body)
if decodedData and decodedData.search and decodedData.search[1] then
return decodedData.search[1].id
end
end
return nil
end
-- Main function to be called from Wiktionary
function p.findWikidataItem(frame)
local args = frame.args
local pageName = args[1] or mw.title.getCurrentTitle().text
local wikidataItem = getWikidataItem(pageName)
if wikidataItem then
return "Best match Wikidata item for '" .. pageName .. "': " .. wikidataItem
else
return "No Wikidata item found for '" .. pageName .. "'."
end
end
return p