From e8785a87bb48e17848d53a9d0973797dd099a3cf Mon Sep 17 00:00:00 2001 From: p5rqvkz4o <493566904@qq.com> Date: Fri, 18 Apr 2025 09:14:00 +0800 Subject: [PATCH] =?UTF-8?q?=E6=95=B0=E5=AD=97=E8=BD=AC=E5=8C=96=E5=87=BD?= =?UTF-8?q?=E6=95=B0=20=E8=BE=93=E5=85=A5=EF=BC=9A=E5=8D=95=E4=B8=AA?= =?UTF-8?q?=E6=96=87=E6=9C=AC=20=E8=BE=93=E5=87=BA=EF=BC=9A=E5=B0=86?= =?UTF-8?q?=E6=96=87=E6=9C=AC=E4=B8=AD=E8=8B=B1=E6=96=87=E6=95=B0=E5=AD=97?= =?UTF-8?q?=E8=BD=AC=E5=8C=96=E4=B8=BA=E9=98=BF=E6=8B=89=E4=BC=AF=E6=95=B0?= =?UTF-8?q?=E5=AD=97=EF=BC=88=E5=AD=98=E5=9C=A8=E5=85=A8=E9=83=A8=E5=B0=8F?= =?UTF-8?q?=E5=86=99=E7=9A=84=E5=89=AF=E4=BD=9C=E7=94=A8=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