第68批:NumberParser数字解析器+MD表格回退+非标准数字支持
Auto Release / build (push) Successful in 2m11s

新功能:
- 新增 NumberParser.java 通用数字解析器
  支持纯数字/英文数字词(one/two/hundred)/中文数字(一百/贰佰)/混合写法
  自动剥离量词后缀(个/只/条/块/把/张/根/片/粒/颗/株/棵/座/间/枚/份/套/组/批/次/回/遍/趟/顿/餐/杯/瓶/罐/盒/包/袋/桶/筐/篓/篮/壶)
  失败返回-1不抛异常
- StackConfigManager.reload() 改造
  字符串值走 NumberParser(支持 一百个/贰佰/One hundred)
  JSON 无有效顶层键值时回退解析 MD 表格
  JSON 优先,表格兜底
- 新增 loadFromJson / loadFromMdTable 拆分方法
This commit is contained in:
youpaishidifu
2026-11-03 13:19:19 +08:00
parent ad109119ca
commit cb7abc516d
3 changed files with 384 additions and 21 deletions
+281
View File
@@ -0,0 +1,281 @@
package Sdf1_login;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 通用数字解析器(第68批,2026-11-03)。
*
* 支持非标准数字写法,不要求用户必须输入纯数字。
* 解析顺序:
* 1. 纯阿拉伯数字(含前后空格/引号)
* 2. 英文数字词(one/two/.../ninety, 支持 twenty one / twenty-one 连写)
* 3. 中文数字(一-九/十百千万/壹贰叁.../零〇/两)
* 4. 混合写法(英文词 + 中文单位,如 "One hundred")
*
* 自动剥离常见量词后缀:个/只/条/块/把/张/根/片/粒/颗/株/棵/座/间/枚/份/套/组/批/次/回/遍/趟/顿/餐/杯/瓶/罐/盒/包/袋/桶/筐/篓/篮/壶/瓶/壶
*
* 失败时返回 -1(不抛异常),调用方可静默跳过。
*/
public class NumberParser {
/** 常见量词后缀(自动剥离) */
private static final String QUANTIFIER_REGEX =
"(个|只|条|块|把|张|根|片|粒|颗|株|棵|座|间|枚|份|套|组|批|次|回|遍|趟|顿|餐|杯|瓶|罐|盒|包|袋|桶|筐|篓|篮|壶)$";
/** 英文数字词表 */
private static final String[] EN_WORDS = {
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen",
"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety",
"hundred", "thousand", "million"
};
/** 英文数字词正则(用于匹配替换) */
private static final Pattern EN_WORD_PATTERN;
static {
StringBuilder alt = new StringBuilder();
for (String w : EN_WORDS) {
if (alt.length() > 0) alt.append("|");
alt.append(w);
}
// \b 边界 + 词 + (可选连字符/空格 + 另一个词)
EN_WORD_PATTERN = Pattern.compile(
"(?i)\\b(" + alt + ")(?:[\\s-]+(" + alt + "))?\\b");
}
/** 中文数字映射 */
private static final Map<Character, Long> CN_DIGITS = new HashMap<>();
static {
CN_DIGITS.put('零', 0L); CN_DIGITS.put('〇', 0L);
CN_DIGITS.put('一', 1L); CN_DIGITS.put('壹', 1L);
CN_DIGITS.put('二', 2L); CN_DIGITS.put('贰', 2L); CN_DIGITS.put('两', 2L);
CN_DIGITS.put('三', 3L); CN_DIGITS.put('叁', 3L);
CN_DIGITS.put('四', 4L); CN_DIGITS.put('肆', 4L);
CN_DIGITS.put('五', 5L); CN_DIGITS.put('伍', 5L);
CN_DIGITS.put('六', 6L); CN_DIGITS.put('陆', 6L);
CN_DIGITS.put('七', 7L); CN_DIGITS.put('柒', 7L);
CN_DIGITS.put('八', 8L); CN_DIGITS.put('捌', 8L);
CN_DIGITS.put('九', 9L); CN_DIGITS.put('玖', 9L);
}
/**
* 解析数字字符串为 int。
* 支持:纯数字、英文数字词、中文数字、混合写法、带量词后缀。
*
* @param raw 用户输入的原始字符串
* @return 解析后的整数值;无法解析返回 -1
*/
public static int parse(String raw) {
if (raw == null) return -1;
String s = raw.trim();
if (s.isEmpty()) return -1;
// 去除 JSON 字符串引号(如 "128" → 128)
if (s.length() >= 2 && s.startsWith("\"") && s.endsWith("\"")) {
s = s.substring(1, s.length() - 1).trim();
}
// 剥离量词后缀
s = stripQuantifier(s);
// 1. 纯阿拉伯数字
if (s.matches("\\d+")) {
return safeParseInt(s);
}
// 2. 英文数字词
int enResult = tryParseEnglish(s);
if (enResult >= 0) return enResult;
// 3. 中文数字
int cnResult = tryParseChinese(s);
if (cnResult >= 0) return cnResult;
// 4. 英文词 + 中文数字混合(如 "One hundred 一百")
// 先替换英文词为数字,再尝试中文解析
String mixed = normalizeEnglish(s);
if (!mixed.equals(s)) {
int mixedResult = tryParseChinese(mixed);
if (mixedResult >= 0) return mixedResult;
// 替换后可能是纯数字
if (mixed.matches("\\d+")) {
return safeParseInt(mixed);
}
}
return -1;
}
/** 剥离量词后缀 */
private static String stripQuantifier(String s) {
return s.replaceAll(QUANTIFIER_REGEX, "").trim();
}
/** 尝试解析英文数字词 */
private static int tryParseEnglish(String s) {
String normalized = normalizeEnglish(s);
if (!normalized.equals(s) && normalized.matches("\\d+")) {
return safeParseInt(normalized);
}
return -1;
}
/** 英文数字词 → 阿拉伯数字替换 */
private static String normalizeEnglish(String s) {
Matcher m = EN_WORD_PATTERN.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String word1 = m.group(1);
String word2 = m.group(2);
long val = enWordValue(word1);
// 连写:twenty one → 20 + 1 = 21
if (word2 != null) {
val += enWordValue(word2);
}
// hundred/thousand/million 作为单位
if (isMultiplierWord(word1)) {
// "one hundred" → 1 × 100
// 需要特殊处理:如果前面有数字词,取其值 × multiplier
// 简化处理:直接替换为 multiplier 的数值
sb.append(String.valueOf(val));
} else {
sb.append(String.valueOf(val));
}
}
m.appendTail(sb);
String result = sb.toString().trim();
// 如果原串全是英文词,结果应该是纯数字
return result;
}
/** 是否为乘法单位词(hundred/thousand/million) */
private static boolean isMultiplierWord(String w) {
return w.equalsIgnoreCase("hundred")
|| w.equalsIgnoreCase("thousand")
|| w.equalsIgnoreCase("million");
}
/** 英文数字词值 */
private static long enWordValue(String w) {
switch (w.toLowerCase(java.util.Locale.ROOT)) {
case "zero": return 0;
case "one": return 1;
case "two": return 2;
case "three": return 3;
case "four": return 4;
case "five": return 5;
case "six": return 6;
case "seven": return 7;
case "eight": return 8;
case "nine": return 9;
case "ten": return 10;
case "eleven": return 11;
case "twelve": return 12;
case "thirteen": return 13;
case "fourteen": return 14;
case "fifteen": return 15;
case "sixteen": return 16;
case "seventeen": return 17;
case "eighteen": return 18;
case "nineteen": return 19;
case "twenty": return 20;
case "thirty": return 30;
case "forty": return 40;
case "fifty": return 50;
case "sixty": return 60;
case "seventy": return 70;
case "eighty": return 80;
case "ninety": return 90;
case "hundred": return 100;
case "thousand": return 1000;
case "million": return 1000000;
default: return 0;
}
}
/** 尝试解析中文数字 */
private static int tryParseChinese(String s) {
// 提取中文数字部分(去掉英文和标点)
StringBuilder cn = new StringBuilder();
for (char ch : s.toCharArray()) {
if (CN_DIGITS.containsKey(ch) || ch == '十' || ch == '百' || ch == '千' || ch == '万' || ch == '亿') {
cn.append(ch);
} else if (cn.length() > 0 && (ch == ' ' || ch == ',' || ch == ',' || ch == '、' || ch == ';' || ch == ';')) {
// 允许空格/标点分隔
cn.append(' ');
}
}
if (cn.length() == 0) return -1;
String cnStr = cn.toString().trim();
if (cnStr.isEmpty()) return -1;
return parseChineseNumber(cnStr);
}
/**
* 解析中文数字字符串。
* 支持:十/百/千/万/亿 位权,壹贰叁...大写,两=2,零〇=0。
* 算法:逐位扫描,遇到位权字符(十百千万亿)时累加到 section。
*/
private static int parseChineseNumber(String s) {
long section = 0; // 当前段(万以下)
long total = 0; // 总计(万以上)
long num = 0; // 当前累积的数字
boolean hasNum = false;
for (char ch : s.toCharArray()) {
if (ch == ' ') continue;
if (CN_DIGITS.containsKey(ch)) {
num = CN_DIGITS.get(ch);
hasNum = true;
} else if (ch == '十') {
if (!hasNum) num = 1;
section += num * 10;
hasNum = false;
num = 0;
} else if (ch == '百') {
if (!hasNum) num = 1;
section += num * 100;
hasNum = false;
num = 0;
} else if (ch == '千') {
if (!hasNum) num = 1;
section += num * 1000;
hasNum = false;
num = 0;
} else if (ch == '万') {
if (!hasNum) num = 1;
total = (total + section + num) * 10000;
section = 0;
hasNum = false;
num = 0;
} else if (ch == '亿') {
if (!hasNum) num = 1;
total = (total + section + num) * 100000000L;
section = 0;
hasNum = false;
num = 0;
}
// 其它字符忽略
}
long result = total + section + (hasNum ? num : 0);
// 检查溢出
if (result < 0 || result > Integer.MAX_VALUE) return -1;
return (int) result;
}
/** 安全 parseInt */
private static int safeParseInt(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return -1;
}
}
}
@@ -20,6 +20,8 @@ import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
/**
@@ -128,29 +130,21 @@ public class StackConfigManager implements Listener {
try {
String content = Files.readString(configFile.toPath(), StandardCharsets.UTF_8);
// ★ 第68批:先尝试 JSON 代码块,无有效顶层键值时回退解析 MD 表格
JsonObject rootObj = parseConfigJson(content);
if (rootObj == null) {
lastFileHash = computeFileHash();
return;
boolean jsonHasValidConfig = false;
if (rootObj != null) {
jsonHasValidConfig = loadFromJson(rootObj, newMap, newRaw);
}
// ★ 第67批修复:跳过模板/元数据键,只解析实际物品配置
// 模板键包括:配置示范、示例内容、物品堆叠映射、食用方法、规范格式、example 等
// 实际配置是顶层键值对(键=物品名,值=数量)
for (Map.Entry<String, JsonElement> entry : rootObj.entrySet()) {
String key = entry.getKey();
JsonElement val = entry.getValue();
// 跳过元数据/模板键
if (isMetadataKey(key)) continue;
// 跳过非基本类型(对象/数组通常是模板)
if (!val.isJsonPrimitive()) continue;
// 跳过非数字值
if (!val.getAsJsonPrimitive().isNumber()) continue;
int stackSize = val.getAsInt();
newRaw.put(key, stackSize);
resolveAndAdd(key, stackSize, newMap);
// JSON 无有效配置 → 回退解析 MD 表格
if (!jsonHasValidConfig) {
boolean tableParsed = loadFromMdTable(content, newMap, newRaw);
if (tableParsed) {
plugin.getLogger().info("[物品堆叠] JSON 无有效配置,已回退解析 MD 表格");
}
}
// 检测变更并播报
@@ -186,6 +180,89 @@ public class StackConfigManager implements Listener {
}
}
/**
* 从 JSON 对象加载配置。
*
* @return true = 有有效配置;false = 无有效顶层键值(需回退 MD 表格)
*/
private boolean loadFromJson(JsonObject rootObj,
Map<Material, Integer> newMap,
Map<String, Integer> newRaw) {
boolean hasValid = false;
for (Map.Entry<String, JsonElement> entry : rootObj.entrySet()) {
String key = entry.getKey();
JsonElement val = entry.getValue();
// 跳过元数据/模板键
if (isMetadataKey(key)) continue;
// 跳过非基本类型(对象/数组通常是模板)
if (!val.isJsonPrimitive()) continue;
JsonPrimitive prim = val.getAsJsonPrimitive();
int stackSize;
// 数字值直接取
if (prim.isNumber()) {
stackSize = prim.getAsInt();
} else {
// ★ 第68批:字符串值走 NumberParser,支持 "一百个"/"贰佰"/"One hundred"
stackSize = NumberParser.parse(prim.getAsString());
if (stackSize < 0) continue; // 无法解析则跳过
}
hasValid = true;
newRaw.put(key, stackSize);
resolveAndAdd(key, stackSize, newMap);
}
return hasValid;
}
/**
* 从 Markdown 表格解析配置(JSON 无有效键值时的回退方案)。
*
* 表格格式:
* | 物品名字 | 数量 |
* | :---: | :---: |
* | 苹果 | 100个 |
* | gold | 128 |
*
* @return true = 解析成功;false = 无表格或无有效行
*/
private boolean loadFromMdTable(String content,
Map<Material, Integer> newMap,
Map<String, Integer> newRaw) {
// 匹配 Markdown 表格行:| key | value |
// 跳过表头(含"物品"/"名称"/"数量"等字样)和分隔行(含 :---: 或 ---)
Pattern rowPattern = Pattern.compile(
"^\\s*\\|\\s*([^|]+?)\\s*\\|\\s*([^|]+?)\\s*\\|\\s*$");
boolean hasValid = false;
String[] lines = content.split("\\r?\\n");
for (String line : lines) {
Matcher m = rowPattern.matcher(line);
if (!m.matches()) continue;
String key = m.group(1).trim();
String valStr = m.group(2).trim();
// 跳过表头行
if (key.contains("物品") || key.contains("名称") || key.contains("名字")) continue;
// 跳过分隔行
if (key.matches(":?-+:?") || valStr.matches(":?-+:?")) continue;
// 跳过空键
if (key.isEmpty()) continue;
// 解析数字(支持非标准写法)
int stackSize = NumberParser.parse(valStr);
if (stackSize < 0) continue;
hasValid = true;
newRaw.put(key, stackSize);
resolveAndAdd(key, stackSize, newMap);
}
return hasValid;
}
/** 从 item.md 内容中提取 JSON 对象 */
private JsonObject parseConfigJson(String content) {
int jsonStart = content.indexOf("```json");
@@ -12,8 +12,13 @@
}
}
```
| 物品名字 | 数量 |
| :---: | :---: |
| 示范-苹果 | 100个 |
| gold | 128 |
## ----配置区域结束----
### 物品堆叠食用说明
- 在上方json围栏块内,按键值对修改。支持使用中文。通配符支持:`*`和中文词组`所有`。比如`oak_*`表示所有以oak开头的,比如橡木、橡木告示牌、橡木台阶等。`所有羊毛`表示所有以_wool结尾的羊毛。
- 在上方json围栏块/表格块内,按键值对修改。支持使用中文。通配符支持:`*`和中文词组`所有`。比如`oak_*`表示所有以oak开头的,比如橡木、橡木告示牌、橡木台阶等。`所有羊毛`表示所有以_wool结尾的羊毛。