检测单个字符串分数(例如:½)并将其更改为更长的字符串? [英] Detect single string fraction (ex: ½ ) and change it to longer string?

查看:63
本文介绍了检测单个字符串分数(例如:½)并将其更改为更长的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:"32 ½ 不是很热" to x = "info: 32, numerator = 1, denominator = 2"

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

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

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

解决方案

好像有 19 个这样的表格 (这里),它们都以 VLGAR FRACTION 的名字开头.

导入unicodedatadeffraction_finder(s):对于 c in s:尝试:名称 = unicodedata.name(c)除了值错误:继续if name.startswith('庸俗分数'):标准化 = unicodedata.normalize('NFKC', c)分子、斜线、分母 = normalized.partition('⁄')收益率c,int(分子),int(分母)

演示:

<预><代码>>>>s = "32 ½ 不是很热 ">>>打印(*fraction_finder(s))('½', 1, 2)

ex: "32 ½ is not very hot " to x = "info: 32, numerator = 1, denominator = 2"

Note: it could be 3/9, but it cannot be simplified into 1/3 aka literally get what is in the string.

I need to detect the fractional string in a longer string and expand the information to a more usable form.

½ has been given to me decoded and is a string with length one.

解决方案

There seem to be 19 such forms (here) and they all start with the name 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)

Demo:

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

这篇关于检测单个字符串分数(例如:½)并将其更改为更长的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆