美文网首页
python将阿拉伯数字、年份、%转成中文大写

python将阿拉伯数字、年份、%转成中文大写

作者: 王文强Python | 来源:发表于2024-08-13 14:15 被阅读0次

数字字符串中遇到 有逗号分隔、小数点、 %‰‱百千万分号、年份 数字时需要转成大写时可以用到下方封装的方法,会在语音转换时用到

class Tools():
    def __init__(self):
        self.chinese_digits = {'0': '零', '1': '一', '2': '二', '3': '三', '4': '四',
                               '5': '五', '6': '六', '7': '七', '8': '八', '9': '九'
                               }
        self.tf = Transform()

    def replacebfh(self, text):
        try:
            bfb = re.findall(r'(-?\d+\.?\d+?[%‰‱])', text)
            text = self._replacebfh(bfb, text)
            bfb2 = re.findall(r'(-?\d+[%‰‱])', text)
            text = self._replacebfh(bfb2, text)
            return text
        except Exception as e:
            return text

    def _replacebfh(self,bfb,text):
        if bfb:
            bfb.sort(key=lambda i: len(i), reverse=True)
            for b in bfb:
                if '%' in b:
                    b2 = '负百分之' + b[1:-1] if b.startswith('-') else '百分之' + b[:-1]
                    text = text.replace(b, b2)
                elif '‰' in b:
                    b2 = '负千分之' + b[1:-1] if b.startswith('-') else '千分之' + b[:-1]
                    text = text.replace(b, b2)
                elif '‱' in b:
                    b2 = '负万分之' + b[1:-1] if b.startswith('-') else '万分之' + b[:-1]
                    text = text.replace(b, b2)
        return text

    def replacenumb(self, text):
        try:
            numbs = re.findall(r'(-?\d{1,3}(?:,\d{3})*(?:\.\d+)?)', text)
            if numbs:
                numbs = [r for r in numbs if ',' in r]
                numbs.sort(key=lambda i: len(i), reverse=True)

                for n in numbs:
                    n2 = an2cn(n.replace(',', ''))
                    text = text.replace(n, n2)

                numbs2 = re.findall(r'(-?\d{1,}\.?\d{0,})', text)
                numbs2.sort(key=lambda i: len(i), reverse=True)

                for n in numbs2:
                    n2 = an2cn(n.replace(',', ''))
                    text = text.replace(n, n2)

            return text
        except Exception as e:
            return text

    def replaceyears(self, text):
        try:
            pattern = r'(?:\d{4}年)?(?:\d{1,2}月)?(?:\d{1,2}日)?|\d{4}[年/-]\d{1,2}[月/-]?\d{1,2}|\d{4}[年/-]\d{1,2}'
            years = re.findall(pattern, text)
            if years:
                years = [y for y in years if y]
                years.sort(key=lambda i: len(i), reverse=True)
                for y in years:
                    for fm in ['%Y-%m-%d','%Y/%m/%d','%Y年%m月%d日','%Y-%m','%Y/%m','%Y年%m月']:
                        try:
                            y2 = datetime.strftime(datetime.strptime(y, fm),'%Y年%m月') if fm in ['%Y-%m','%Y/%m','%Y年%m月'] else datetime.strftime(datetime.strptime(y, fm),'%Y年%m月%d日')
                            y1 = self.tf.transform(y2, 'an2cn')
                            text = text.replace(y, y1)
                            break
                        except Exception as e:
                            pass
                    else:
                        if y[:4].isnumeric():
                            y1 = ''
                            for i in y[:4]:
                                y1 += self.chinese_digits.get(i, '')
                            y1 = y1 + y[4:]
                            text = text.replace(y, y1)

            return text
        except Exception as e:
            return text


    def clean_numb(self, text):
        text = self.replacebfh(text)
        text = self.replaceyears(text)
        text = self.replacenumb(text)
        return text

测试如下:

example_string = "2023年的收入是1,234.56美元,其中AAPL的股票占了大部分。1,234美元 或 12,345,678美元 或12,345美元,678.52美元 或678.52美元,2023年,2023年5月6日,2023-05-06,1958/3/6或者2013年05月,2020年9月,26534 或 2023huozh 5.32% 56% 或5% 0.32%,635269% , 5646321‰, 85.023265820‱"

t = Tools()
text = t.clean_numb(example_string)
print(text)

打印出来的结果如下:
'二零二三年的收入是一千二百三十四点五六美元,其中AAPL的股票占了大部分。一千二百三十四美元 或 一千二百三十四万五千六百七十八美元 或一万二千三百四十五美元,六百七十八点五二美元 或六百七十八点五二美元,二零二三年,二零二三年5月6日,二零二三-05-06,一九五八/3/6或者二零一三年05月,二零二零年9月,二万六千五百三十四 或 二千零二十三huozh 百分之五点三二 百分之56 或5% 百分之零点三二,百分之六十三万五千二百六十九 , 千分之五百六十四万六千三百二十一, 万分之八十五点零二三二六五八二零'

相关文章

网友评论

      本文标题:python将阿拉伯数字、年份、%转成中文大写

      本文链接:https://www.haomeiwen.com/subject/pjljkjtx.html