python - 将句子中的数字转换为python中的单词

标签 python numbers

我有一个文本,其中句子中有一些数字,我只想将数字转换为单词格式。我该如何解决这个问题。我已经为此编写了一个代码,但它不起作用,因为我将文本传递给“函数”而不是数字。我该怎么做

我试过下面的代码。

import num2words


def convert_num_to_words(utterance):
      utterance = num2words(utterance)
      return utterance

transcript = "If you can call the merchant and cancelled the transaction and confirm from them that they will not take the payment the funds will automatically be credited back into your account after 24 hours as it will expire on 11/04 Gemma"

print(convert_num_to_words("transcript"))

预期结果是

“如果您可以调用商家并取消交易并向他们确认他们不会接受付款,则资金将在 24 小时后自动记入您的帐户,因为它将于 11 月 4 日 Gemma 到期”

即文本中的数字 24 应转换为单词(二十四)

最佳答案

你需要对字符串中的每个单词都这样做,并且只有当它是数字时,并且还要删除 transcript 旁边的引号,同时执行 num2words.num2words(...) 不仅仅是 num2words(...):

import num2words

def convert_num_to_words(utterance):
      utterance = ' '.join([num2words.num2words(i) if i.isdigit() else i for i in utterance.split()])
      return utterance

transcript = "If you can call the merchant and cancelled the transaction and confirm from them that they will not take the payment the funds will automatically be credited back into your account after 24 hours as it will expire on 11/04 Gemma"

print(convert_num_to_words(transcript))

关于python - 将句子中的数字转换为python中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56733012/

相关文章:

c# - 将 int 转换为 System.Drawing.Brushes.SomeColor?

python - 无法使用 Python 截断数字

numbers - 阿拉伯数字识别

python - 在 Azure 容器实例中部署机器学习模型时如何访问所有已注册的模型?

python - CSV 到 dict,dict 找不到该项目

python - 有没有一种简单的方法可以将一个环境中的相同 Python 库安装到新的 Python 环境中?

python - 如何访问不同类的对象?

Javascript 正则表达式格式化程序现在允许具有 , 和 的数字。同时

javascript - Parseint——用 e+ chop

python - Python 3 中 str.translate 的自定义表