跳转到内容

模組:沙盒/Number2

维基百科,自由的百科全书
local p = {}

local mError = require('Module:Error')

-- 取自[[Module:NumberToChinese]]
function stringToTable(s) --字串轉陣列
	local t = {}
	for i = 1, #s do
		t[i] = s:sub(i, i)
	end
	return t
end

-- local standard = {{'〇', '一', '二', '三', '四', '五', '六', '七', '八', '九'}, {'零', '壹', '貳', '叄', '䦉', '伍', '陸', '柒', '捌', '玖'}}
-- local decimal = {{'', '十', '百', '千'}, {'', '拾', '佰', '仟'}}
local large = {'', '萬', '億', '兆', '京', '垓', '秭', '穰', '溝', '澗', '正', '載', '極', '恆河沙', '阿僧祇', '那由他', '不可思議', '無量', '大數'}
-- end
local standard_reverse = {
	{
		['〇'] = '0',['一'] = '1',['二'] = '2',['三'] = '3',['四'] = '4',['五'] = '5',['六'] = '6',['七'] = '7',['八'] = '8',['九'] = '9'
	},{
		['零'] = '0',['壹'] = '1',['貳'] = '2',['叄'] = '3',['䦉'] = '4',['伍'] = '5',['陸'] = '6',['柒'] = '7',['捌'] = '8',['玖'] = '9'
	}
}
local decimal_reverse = {
	{
		'千','百','十',''
	},{
		'仟','佰','拾',''
	}
}

local function chinese_to_num (text, type)
	local this_standard = standard_reverse[type]
	local this_decimal = decimal_reverse[type]
	local i = ''
	local num = ''
	for _, v in ipairs(this_decimal) do
		if text:match(v) then
			i = text:match('(.-)' .. v)
			if v == this_decimal[3] then
				i = v
				num = num .. '1'
			else
				i = this_standard[i]
				if not i then
					return nil
				end
				num = num .. i
			end
			text = text:gsub(i .. v)
		else
			num = num .. '0'
		end
	end
	return num
end

function p._ChineseToNumber (text, type)
	if not type then
		type = 1
	elseif not standard[type] then
		return nil
	end
	local num = ''
	if text:sub(1, 1) == '正' then
		text = text:sub(2, #text)
	elseif number:sub(1, 1) == '負' then
		num = '-'
		text = text:sub(2, #text)
	end
	local i = ''
	local num_table = {}
	for _, v in ipairs(large) do
		if _ > 1 then
			i = mw.text.split(text, large, v)
			if i[2] then
				num_table[#num_table + 1] = chinese_to_num(i[1], type)
				text = i[2]
			else
				num_table[#num_table + 1] = chinese_to_num(i[1], type)
				break;
			end
		end
	end
	local s = #num_table
	while s > 0 do
		num = num .. num_table[s]
		s = s - 1
	end
	return num
end