在python中把句子中的数字转换成单词

2024-04-25 21:59:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本,其中我有一些数字在句子中,我只想把数字转换成word格式。我怎样才能解决这个问题。我已经为此编写了一个代码,但这不起作用,因为我传递的是文本,而不是数字。我该怎么做

我尝试了以下代码。你知道吗

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 Gemma到期。”

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


Tags: andtheto代码文本convert数字帐户
1条回答
网友
1楼 · 发布于 2024-04-25 21:59:36

您需要对字符串中的每个单词执行此操作,并且仅当它是数字时,还需要删除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))

相关问题 更多 >