From f5c545cba278c9cbc2c3a6b6889519a35abdab59 Mon Sep 17 00:00:00 2001 From: p5rqvkz4o <493566904@qq.com> Date: Fri, 18 Apr 2025 08:55:16 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BE=93=E5=85=A5=E5=8D=95=E4=B8=AA=E5=8F=A5?= =?UTF-8?q?=E5=AD=90=20=20=20=E8=BE=93=E5=87=BA=E5=B0=86=E8=8B=B1=E6=96=87?= =?UTF-8?q?=E6=95=B0=E5=AD=97=E8=BD=AC=E5=8C=96=E4=B8=BA=E9=98=BF=E6=8B=89?= =?UTF-8?q?=E4=BC=AF=E6=95=B0=E5=AD=97=E7=9A=84=E5=8F=A5=E5=AD=90=20=20=20?= =?UTF-8?q?=EF=BC=88=E4=BB=85=E5=87=BD=E6=95=B0=E5=AE=9E=E7=8E=B0=20?= =?UTF-8?q?=E5=8F=AF=E4=BD=9C=E4=B8=BA=E5=A4=B4=E6=96=87=E4=BB=B6=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Code_reticent/Snt2Int.py | 61 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Code_reticent/Snt2Int.py diff --git a/Code_reticent/Snt2Int.py b/Code_reticent/Snt2Int.py new file mode 100644 index 0000000..fa1ba9e --- /dev/null +++ b/Code_reticent/Snt2Int.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +""" +Created on Fri Apr 18 08:47:33 2025 + +@author: 缄默 +""" + +def Snt2Int(text): + # 定义数字词与值的映射 + number_words = { + 'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, + 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, + 'eleven': 11, 'twelve': 12, 'thirteen': 13, 'fourteen': 14, + 'fifteen': 15, 'sixteen': 16, 'seventeen': 17, 'eighteen': 18, + 'nineteen': 19, 'twenty': 20, 'thirty': 30, 'forty': 40, + 'fifty': 50, 'sixty': 60, 'seventy': 70, 'eighty': 80, 'ninety': 90 + } + units = {'hundred': 100, 'thousand': 1000, 'million': 1000000, 'billion': 1000000000} + + words = text.lower().replace('-', ' ').split() # 预处理:转为小写并分割 + result = [] + current_sequence = [] + + for word in words: + # 判断是否为数字词或单位词(忽略“and”) + if word in number_words or word in units: + current_sequence.append(word) + else: + if current_sequence: + result.append(_convert_sequence(current_sequence, number_words, units)) + current_sequence = [] + result.append(word) + + # 处理最后的数字序列 + if current_sequence: + result.append(_convert_sequence(current_sequence, number_words, units)) + + return ' '.join(map(str, result)) + +def _convert_sequence(sequence, number_words, units): + has_units = any(word in units for word in sequence) + if has_units: + total = 0 + current_value = 0 + for word in sequence: + if word in units: + unit = units[word] + if unit == 100: + current_value *= unit + total += current_value + current_value = 0 + elif unit in (1000, 1000000): + total += current_value + total *= unit + current_value = 0 + else: + current_value += number_words[word] + total += current_value + return total + else: + return int(''.join(str(number_words[word]) for word in sequence)) \ No newline at end of file