在Python中将句子中的数字转换为单词

时间:2019-06-24 08:53:11

标签: 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/04年杰玛到期” / p>

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

1 个答案:

答案 0 :(得分:4)

您需要对字符串的每个单词都进行此操作,并且仅当它是数字形式时,并删除transcript旁边的引号,也不仅要num2words.num2words(...),还要num2words(...):< / p>

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))