Mycroft Core 自然语言解析指南:mycroft.util.parse 模块完全详解

原创2026-10-14 11:49:531,901 阅读
文章标签:人工智能语音交互助手智能硬件

Mycroft Core 自然语言解析指南:mycroft.util.parse 模块完全详解

mycroft.util.parse 是 Mycroft Core 中面向自然语言解析的工具模块,负责把人类口语/文本中表达的数字、日期时间、时长、性别等概念转换成标准的计算机可读格式(datetime、timedelta、float 等),并配套提供文本归一化与模糊匹配能力,是 Mycroft 实现多语言本地化(localization)的关键一环。本文以官方 API 文档 doc/source/mycroft.util.parse.rst 为主线,结合模块源码 mycroft/util/parse.py、单元测试 test/unittests/util/test_parse.py 以及核心组件中的真实调用场景,系统讲解 8 个 API 函数的参数、返回值、行为细节与实战用法。读完本文,你将能够在自己的 Mycroft Skill 中熟练完成"把用户自然语言转成可计算数据"的完整处理流程。

一、模块定位:Skill 开发者的"自然语言到数据"翻译层

从源码模块 docstring(mycroft/util/parse.py)可以看到该模块的设计意图:

The mycroft.util.parse module provides various parsing functions for things like numbers, times, durations etc. It's intention is to convert naturally expressed concepts into standard computer readable formats. Doing this also enables localization.

即:把人类自然表达的概念转换为标准计算机格式,同时天然支持多语言本地化。模块还提供了一些与之配套的实用函数(如基础模糊匹配)。

值得说明的是,该模块本身并不实现具体解析算法,而是将大部分实际解析工作委托给 Mycroft 官方的多语言解析库 lingua-franca(在 requirements/requirements.txt 中锁定版本为 lingua-franca==0.4.2)。mycroft.util.parse 的角色是:

  • 重新导出 lingua-franca 的 extract_duration、extract_number、extract_numbers、fuzzy_match、get_gender、match_one、normalize 等函数(见 mycroft/util/parse.py);
  • 对 extract_datetime 做了一层 Mycroft 特有的包装:用 mycroft.util.time.now_local() 提供基于用户配置时区的默认锚点时间(mycroft/util/parse.py),并与 mycroft.util 包级导出打通(mycroft/util/init.py)。

因此,Skill 开发者既可以通过 from mycroft.util.parse import ... 精确导入,也可以直接使用 mycroft.util.extract_datetime、mycroft.util.extract_number、mycroft.util.normalize 这些快捷入口。

二、文本归一化:normalize

normalize 是使用频率最高的基础函数之一,负责把口语化的文本规整为便于后续匹配与解析的"干净"形式。

参数与核心行为

  • text (str):待处理的文本;
  • remove_articles (bool):是否移除冠词(如 a、an、the),默认 True;
  • contractions (bool):是否展开英文缩写(如 it's → it is),默认 True;
  • lang (str):BCP-47 语言代码,None 时使用默认 locale。

典型行为示例(源自单元测试)

归一化主要做三件事:

  1. 压缩多余空白:" this is a test " → "this is test";
  2. 拼写数字转阿拉伯数字:"this is a one two three test" → "this is 1 2 3 test","that's a ten eleven twelve test" → "that is 10 11 12 test";
  3. 展开缩写:"ain't" → "is not","could've" → "could have","gonna" → "going to","he's" → "he is","what's the weather like" → "what is weather like"。

在是否移除冠词方面,测试给出了精确预期(test/unittests/util/test_parse.py):

normalize("this is a test", remove_articles=True)      # "this is test"
normalize("this is the test", remove_articles=True)    # "this is test"
normalize("this is an extra test", remove_articles=False)  # "this is an extra test"

核心组件中的真实调用

normalize 深度嵌入 Mycroft 的消息与意图处理链路:

  • 消息残句提取:Message.utterance_remainder() 先用 normalize 规整原始 utterance,再按 __tags__ 中的实体词做整词替换,最后再次 normalize 输出(mycroft/messagebus/message.py)。例如用户说 "Turn on the family room light",在 "turn on" 与 "light" 被 Adapt 消费后,剩下 " the family room " 会被归一化成 "family room";
  • 意图匹配预处理:_normalize_all_utterances 在适配器分发前生成"原始 utterance + 归一化版本"的配对,供 Adapt / Padatious / Fallback 等意图服务使用,其中 normalize(u.lower(), remove_articles=False) 保留了冠词以维持语义(mycroft/skills/intent_service.py)。

从这些调用可以看出实践建议:做意图关键词匹配前先 normalize,能显著提高命中率,因为缩写、拼写数字和多余空白都被统一了。

三、数字提取:extract_number 与 extract_numbers

数字解析是"定时器、购物、计数"等 Skill 的刚需能力,extract_number 提取单个数字,extract_numbers 提取句中所有数字。

extract_number

  • text (str):输入文本;
  • ordinals (bool):是否解析序数词(first/second/third…),默认 False;
  • short_scale (bool):数值进制是否为 short scale(美式十亿进制),默认 True;
  • lang (str):语言代码。

返回值:成功返回 float;文本中不含数字时返回 False(注意是布尔 False 而非 0,可用于快速判断)。

综合 docstring 与测试用例(test/unittests/util/test_parse.py),它支持以下语法形态:

输入示例 结果 说明
"this is 2 test" 2.0 阿拉伯数字
"twenty two" 22.0 英文拼写数字
"six hundred sixty six" 666.0 复合拼写
"this is the third test"(无 ordinals) 1/3 默认按分数处理
"this is the third test"(ordinals=True) 3.0 序数词
"the thirty sixth one"(ordinals=True) 36.0 复合序数
"one third of a cup" 1/3 分数
"1 and 3/4 cups" 1.75 混合带分数
"one and a half cups" 1.5 口语小数
"quarter cup" 0.25 分数词
"one point five" 1.5 point 小数
"minus 2" / "negative seventy" -2.0 / -70.0 负数
"a couple of beers" 2.0 约定俗成量词
"100%" 100.0 百分比
"two million five hundred thousand tons of spinning metal" 2500000.0 大数
"six trillion"(short_scale=True) 6e12 short scale
"six trillion"(short_scale=False) 6e18 long scale(欧洲十亿进制)
"fraggle" False 无数字返回 False
"fraggle zero" 0.0 含 zero 则正常返回 0

extract_numbers

extract_numbers(text, short_scale=True, ordinals=False, lang=None) 返回 <a href="https://link.gitcode.com/i/9bc0435ff590c529eacbae16febb6926" target="_blank">float, ...] 列表,包含文本中出现的所有数字。测试覆盖了多种组合([test/unittests/util/test_parse.py):

extract_numbers("this is a one two three test")       # [1.0, 2.0, 3.0]
extract_numbers("1 dog, seven pigs, macdonald had a farm, 3 times 5 macarena")
# [1.0, 7.0, 3.0, 5.0]
extract_numbers("third one")                          # [1/3, 1.0]
extract_numbers("third one", ordinals=True)           # [3.0]
extract_numbers("this is a seven eight nine and a half test")  # [7.0, 8.0, 9.5]

注意 "twenty 2" 这类"拼写 + 数字"粘连的情况会合并为 [22.0],而 "twenty twenty two twenty" 则拆分为 [20.0, 22.0, 20.0]——实际行为取决于分词边界,开发时应以测试预期为准。

四、日期时间提取:extract_datetime

这是模块中最具代表性的函数,也是唯一在 Mycroft 侧做了定制包装的函数。它负责从句子中解析人类表达日期的各种常见方式,包括相对日期(如 "5 days from today"、"tomorrow"、"Tuesday")与具体时刻。

函数签名与参数

extract_datetime(text, anchorDate="DEFAULT", lang=None, default_time=None)
  • text (str):待解释文本;
  • anchorDate (datetime, 可选):相对日期计算所基于的"锚点"日期(例如 "tomorrow" 相对哪一天)。默认 "DEFAULT",此时使用 mycroft.util.time.now_local() 返回的用户本地时区当前时间(mycroft/util/time.py),时区取自配置 location.timezone.code,缺失时回退系统时区。若显式传 None,会触发 DeprecationWarning 并同样回退到当前本地时间;
  • lang (str):BCP-47 语言代码,None 使用 get_default_loc();
  • default_time (datetime.time):当输入中没有明确时间时使用的默认时刻,None 时默认 12 AM(午夜)。

模糊时刻的约定取值

文档明确给出了口语化时段词的任意约定值:

时段词 解析值
morning(早晨) 8 AM
afternoon(下午) 3 PM
evening(晚上) 7 PM
未给出/未暗示时间 12 AM(默认)

这些约定在测试中得到印证:"what is the weather on friday morning" → 2017-06-30 08:00,"this afternoon's weather" → 15:00,"this evening's weather" → 19:00(test/unittests/util/test_parse.py)。

返回值与 docstring 示例

返回值是 [datetime, str] 二元组或 None:

  • datetime:提取出的日期时间对象,位于用户本地时区(测试 test_extract_timezone 专门验证了这一点);
  • str:leftover_string,即剔除所有日期时间相关关键词后剩余的原始短语;
  • 若文本中不含任何日期/时间信息,返回 None。

官方 docstring 给出了三个经典示例(mycroft/util/parse.py):

extract_datetime("What is the weather like the day after tomorrow?",
                 datetime(2017, 06, 30, 00, 00))
# [datetime.datetime(2017, 7, 2, 0, 0), 'what is weather like']

extract_datetime("Set up an appointment 2 weeks from Sunday at 5 pm",
                 datetime(2016, 02, 19, 00, 00))
# [datetime.datetime(2016, 3, 6, 17, 0), 'set up appointment']

extract_datetime("Set up an appointment",
                 datetime(2016, 02, 19, 00, 00))
# None

实战行为矩阵(来自测试)

测试文件对时间表达覆盖极为详尽(test/unittests/util/test_parse.py),可总结为以下规律,供开发 Skill 时参考(测试锚点时间为 2017-06-27 13:04,周二):

  • 相对时间:"in a minute" → 13:05,"in a couple hours" → 15:04,"in a week" → 2017-07-04,"in a couple months" → 2017-08-27,"in a decade" → 2027-06-27,"in a millennium" → 3017-06-27;
  • 时刻表达:"at 10:45 pm" → 22:45,"at 7 o'clock" → 晚上 7 点(当前时刻下午 13:04 之后取当天),"at 7 o'clock in the morning" → 次日 07:00,"at 1730" → 17:30,"at 06 30 hours" → 次日 06:30,"at noon" → 12:00,"at midnight" → 00:00;
  • 星期与相对日:"next Tuesday" → 2017-07-04,"this Thursday" → 2017-06-29,"last Monday" → 2017-06-26,"2 days from next Friday at 0500" → 2017-07-09 05:00,"the day after tomorrow" → 2017-06-29;
  • 具体日期:"on august 3rd" → 2017-08-03,"on the 4th of July" → 2017-07-04,"december 3" → 2017-12-03,"on the evening of 5 august 2017" → 2017-08-05 19:00;
  • 残句剥离:"Set the ambush in 1 minute" → [13:05, "set ambush"],"Begin the invasion at 3:45 pm on Thursday" → [2017-06-29 15:45, "begin invasion"]——日期时间词被干净地剔除,便于 Skill 继续处理剩余意图;
  • 模糊时刻消歧(test_extract_ambiguous_time_en):"feed fish at 10 o'clock" 在早上 8:01 锚点时解析为当天 10:00,在 12:01 或晚上 20:01 锚点时则解析为 22:00(即"最近的合理时刻");
  • "May I" 干扰消除(test_extract_date_with_may_I_en):"May I know what time it is tomorrow" 中 "May" 是情态动词而非月份,能正确解析为次日。

五、时长提取:extract_duration

extract_duration(text, lang=None) 用于从句子中提取时长,返回 (timedelta, leftover_string) 二元组;文本中不含时长信息时返回 None。

行为示例(test_extract_duration_en)

extract_duration("10 seconds")            # (timedelta(seconds=10.0), "")
extract_duration("2 hours")               # (timedelta(hours=2), "")
extract_duration("25 weeks")              # (timedelta(weeks=25), "")
extract_duration("seven hours")           # (timedelta(hours=7), "")
extract_duration("7.5 seconds")           # (timedelta(seconds=7.5), "")
extract_duration("Set a timer for 30 minutes")
# (timedelta(minutes=30), "Set a timer for")
extract_duration("Four and a half minutes until sunset")
# (timedelta(minutes=4.5), "until sunset")
extract_duration("eight and a half days thirty nine seconds")
# (timedelta(days=8.5, seconds=39), "")

关键特征:

  • 支持口语小数("four and a half minutes" → 4.5 分钟);
  • 支持多个时长单位叠加("wake me up in three weeks, four hundred ninety seven days, and three hundred 91.6 seconds" → timedelta(weeks=3, days=497, seconds=391.6));
  • 时长表达从文本中剥离后,剩余内容作为 leftover_string 返回,便于继续做意图分析;
  • 空串输入返回 None。

典型应用是定时器/提醒类 Skill:先 extract_duration 拿到 timedelta 换算成秒数交给调度器,再用 leftover_string 确认剩余语义。

六、性别提取:get_gender

get_gender(text, lang=None) 用于提取文本所指对象的语法性别(grammatical gender),返回 "m"(阳性)、"f"(阴性)或 None(中性/无法确定)。这对存在语法性别区分的语言(如葡萄牙语、意大利语)的文本生成很重要。

测试验证(test_gender):

load_language("pt")
get_gender("person", lang="pt")   # None(中性词)
get_gender("vaca", lang="pt")     # 'f'("奶牛"为阴性)
load_language("it")
get_gender('cavallo', lang='it')  # 'm'("马"为阳性)

需要特别留意:该函数仅对已加载语言实现。测试中 get_gender("person") 在默认 en-us 下直接抛出 FunctionNotLocalizedError——这提示开发者使用前务必先确认目标语言已通过 lingua_franca.load_language() 加载,否则需捕获异常或用 lang 参数明确指定支持的语言。

七、模糊匹配:fuzzy_match 与 match_one

这两个函数用于"用户说的话与预置选项并不完全一致"的场景,是意图消歧和选项选择的利器。

fuzzy_match

fuzzy_match(query, target) 基于 Python difflib.SequenceMatcher(mycroft/util/parse.py)计算两个字符串的相似度,返回 0.0 ~ 1.0 的分数。测试给出的行为基准(test_matches):

fuzzy_match("you and me", "you and me") == 1.0      # 完全一致 ≥ 1.0
fuzzy_match("you and me", "you") < 0.5              # 部分包含得分较低
fuzzy_match("You", "you") > 0.5                     # 大小写不敏感程度较高
fuzzy_match("you and me", "you") == fuzzy_match("you", "you and me")  # 对称性
fuzzy_match("you and me", "he or they") < 0.2       # 无关文本得分很低

match_one

match_one(query, choices) 在多个候选中找出最匹配的一个,是 fuzzy_match 的"批量版"。它支持两种输入形态:

  • list 候选:返回 (最佳匹配元素, 得分),如 match_one('fran', ['frank', 'kate', 'harry', 'henry']) → ('frank', ...);
  • dict 候选:键为候选文本、值为关联数据,返回 (关联值, 得分),如 match_one('enry', {'frank': 1, 'kate': 2, 'harry': 3, 'henry': 4}) → (4, ...)。

拼写容错能力很强:'fran' 匹配到 'frank','katt' 匹配到 'kate','enry' 匹配到 'henry'(test_match_one)。

Skill 中的真实用法:选项选择器

match_one 与 extract_number 的组合出现在 MycroftSkill.ask_selection 的实现中(mycroft/skills/mycroft_skill/mycroft_skill.py):

match, score = match_one(resp, options)
if score < min_conf:
    if self.voc_match(resp, 'last'):
        resp = options[-1]
    else:
        num = extract_number(resp, ordinals=True, lang=self.lang)
        resp = None
        if num and num <= len(options):
            resp = options[num - 1]
else:
    resp = match

这是非常有代表性的"双通道"设计:当模糊匹配得分低于阈值时,回退尝试用序数词/数字解析用户选择(如用户说"第二个"),两条路径互为补充,保证交互鲁棒性。

八、使用前置条件与注意事项

  1. 依赖 lingua-franca:所有解析能力最终来自 lingua-franca==0.4.2(requirements/requirements.txt),安装 mycroft-core 依赖时需确保该版本可用;
  2. 语言加载:多语言解析(尤其 get_gender)依赖对应语言包已加载,未加载时会抛 FunctionNotLocalizedError(test/unittests/util/test_parse.py);
  3. 时区语义:extract_datetime 返回的是用户本地时区的 datetime,时区源自配置 location.timezone.code(mycroft/util/time.py),Skill 中做定时调度时应保持同一时区语义;
  4. 返回 False 而非 0:extract_number 无数字时返回布尔 False,判断时不要与数值 0 混淆;
  5. 正常化先行:对原始 STT 文本先 normalize 再匹配或解析,是官方核心组件(意图服务、消息残句)都遵循的流水线惯例。

九、快速上手:一个综合示例

结合上述全部 API,一个"定时器/提醒" Skill 的典型解析流程可以这样组织:

from mycroft.util.parse import normalize, extract_duration, extract_datetime

def handle_reminder(utterance):
    text = normalize(utterance)                     # 1. 归一化
    duration, leftover = extract_duration(text)     # 2. 尝试提取时长
    if duration:
        # leftover 里还保留着"提醒我做什么"的语义
        seconds = duration.total_seconds()
        return "schedule", seconds, leftover
    parsed = extract_datetime(text)                 # 3. 回退:提取日期时间
    if parsed:
        when, remainder = parsed
        return "alarm", when, remainder
    return None, None, None

这也是官方模块 docstring 所强调的核心理念——把自然语言先翻译成标准数据,再交给业务逻辑,从而让每个 Skill 都能复用同一套多语言解析能力。

十、测试验证

模块的正确性由 test/unittests/util/test_parse.py 全面保障,测试覆盖:

  • TestFuzzyMatch:模糊匹配与候选选择的对称性、容错性;
  • TestNormalize:冠词移除、缩写展开、空白压缩、数字转写、组合场景;
  • TestExtractNumber:序数词、分数、小数、负数、量词、大数与进制(short/long scale);
  • TestExtractDuration:单/多单位时长、口语小数、残句剥离、空输入;
  • TestExtractDateTime:近百条日期时间表达(相对时间、时刻、星期、具体日期、模糊时刻消歧、May I 干扰消除),并验证返回的时区正确性;
  • TestGender:多语言语法性别提取与未本地化异常。

运行方式(仓库使用 pytest,配置见 pytest.ini):

pytest test/unittests/util/test_parse.py

如果你正在开发 Mycroft Skill 并需要把用户口语转成结构化数据,mycroft.util.parse 就是官方推荐的第一站:从 normalize 清理文本,到 extract_number/extract_duration/extract_datetime 提取数值,再到 fuzzy_match/match_one 做容错匹配,整套 API 覆盖了自然语言处理中最常用的解析需求,并且天然支持多语言本地化。

登录后查看全文
mycroft-core