Skip to main content

从非结构化文本中提取数量。

项目描述

最新版本 执照 Python 版本 CI 覆盖范围 健康 任务

量子

Python 库,用于从非结构化文本中提取数量、度量及其单位的信息。

演示

在这里试试。

安装

首先,安装sklearn。没有它,Quantulum 仍然可以工作,但它无法消除具有相同名称的单位之间的歧义(例如,英镑作为货币或质量单位)。

然后,

$ pip install quantulum

用法

>>> from quantulum import parser
>>> quants = parser.parse('I want 2 liters of wine')
>>> quants
[Quantity(2, 'litre')]

Quantity类存储从中提取的原始文本的表面,以及匹配的(开始、结束)位置:

>>> quants[0].surface
u'2 liters'
>>> quants[0].span
(7, 15)

还可以使用将解析的数量嵌入文本中的内联解析器(对调试特别有用):

>>> print parser.inline_parse('I want 2 liters of wine')
I want 2 liters {Quantity(2, "litre")} of wine

单位和实体

所有单位(例如liter)和它们关联的实体(例如volume)都与 WikiPedia 进行了核对:

>>> quants[0].unit
Unit(name="litre", entity=Entity("volume"), uri=https://en.wikipedia.org/wiki/Litre)

>>> quants[0].unit.entity
Entity(name="volume", uri=https://en.wikipedia.org/wiki/Volume)

该库包括 290 多个单元和 75 个实体。它还解析拼写出来的数字、范围和不确定性:

>>> parser.parse('I want a gallon of beer')
[Quantity(1, 'gallon')]

>>> parser.parse('The LHC smashes proton beams at 12.8–13.0 TeV')
[Quantity(12.8, "teraelectronvolt"), Quantity(13, "teraelectronvolt")]

>>> quant = parser.parse('The LHC smashes proton beams at 12.9±0.1 TeV')
>>> quant[0].uncertainty
0.1

非标准单位通常没有维基百科页面。解析器仍然会尝试根据它们的维度猜测它们的底层实体:

>>> parser.parse('Sound travels at 0.34 km/s')[0].unit
Unit(name="kilometre per second", entity=Entity("speed"), uri=None)

消歧义

如果解析器检测到歧义,则基于歧义单元或实体的维基百科页面的分类器会尝试猜测正确的:

>>> parser.parse('I spent 20 pounds on this!')
[Quantity(20, "pound sterling")]

>>> parser.parse('It weighs no more than 20 pounds')
[Quantity(20, "pound-mass")]

或者:

>>> text = 'The average density of the Earth is about 5.5x10-3 kg/cm³'
>>> parser.parse(text)[0].unit.entity
Entity(name="density", uri=https://en.wikipedia.org/wiki/Density)

>>> text = 'The amount of O₂ is 2.98e-4 kg per liter of atmosphere'
>>> parser.parse(text)[0].unit.entity
Entity(name="concentration", uri=https://en.wikipedia.org/wiki/Concentration)

操纵

虽然无法在此库中操作数量,但仍有许多不错的选择:

扩大

有关单位的完整列表,请参阅units.json ,有关实体的完整列表,请参阅entities.json。添加单位的标准是:

  • 该单元有(或被重定向到)维基百科页面

  • 该单位是常用的(例如,不是瑞典的计量单位)。

很容易将这两个文件扩展到感兴趣的单位/实体。以下是 entity.json 中的条目示例

{
    "name": "speed",
    "dimensions": [{"base": "length", "power": 1}, {"base": "time", "power": -1}],
    "URI": "https://en.wikipedia.org/wiki/Speed"
}
  • 名称URI是不言自明的。

  • 维度是维度,一个字典列表,每个字典都有一个基数(另一个实体的名称)和一个(一个整数,可以是负数)。

以下是units.json中的条目示例:

{
    "name": "metre per second",
    "surfaces": ["metre per second", "meter per second"],
    "entity": "speed",
    "URI": "https://en.wikipedia.org/wiki/Metre_per_second",
    "dimensions": [{"base": "metre", "power": 1}, {"base": "second", "power": -1}],
    "symbols": ["mps"]
}
  • 名称URI是不言自明的。

  • 表面是引用该单元的字符串列表。该库处理复数,无需指定它们。

  • entity是 entity.json 中实体的名称

  • 维度遵循与entities.json中相同的模式,但基础是另一个单元的名称,而不是另一个实体的名称。

  • 符号是该单位可能的符号和缩写的列表。

所有字段都区分大小写。

项目详情