编程语言
首页 > 编程语言> > python – 检测单个字符串分数(例如:½)并将其更改为更长的字符串?

python – 检测单个字符串分数(例如:½)并将其更改为更长的字符串?

作者:互联网

例如:“32½不是很热”到x =“信息:32,分子= 1,分母= 2”

注意:它可能是3/9,但它不能简化为1/3也就是字面上得到字符串中的内容.

我需要在较长的字符串中检测小数字符串,并将信息扩展为更可用的形式.

½已经给我解码,是一个长度为1的字符串.

解决方法:

似乎有19种这样的形式(here),它们都以VULGAR FRACTION这个名字开头.

import unicodedata

def fraction_finder(s):
    for c in s:
        try:
            name = unicodedata.name(c)
        except ValueError:
            continue
        if name.startswith('VULGAR FRACTION'):
            normalized = unicodedata.normalize('NFKC', c)
            numerator, _slash, denominator = normalized.partition('⁄')
            yield c, int(numerator), int(denominator)

演示:

>>> s = "32 ½ is not very hot "
>>> print(*fraction_finder(s))
('½', 1, 2)

标签:fractions,python,python-3-x,unicode
来源: https://codeday.me/bug/20190929/1832699.html