需要将数字转换为文本文档中的单词

时间:2018-05-21 15:48:47

标签: python

我想将文档中的所有数字更改为单词。按照两个函数检测字符串中的数字,并通过num2word库将其转换为单词。

import num2words
from re import sub

def _conv_num(match):
        word=num2words(match)
        return word

def change_to_word(text):
        normalized_text = sub(r'[^\s]*\d+[^\s]*', lambda m: _conv_num(m.group()), text)
        return normalized_text

当我按照以下代码使用这两个功能时

txt="there are 3 books"
change_to_word(txt)

python发出此错误

  TypeError: 'module' object is not callable

我试图找到一些类似的帖子,但似乎没有身体有相同的问题,或者我没有以适当的方式搜索,所以请帮助我解决方案或链接 问候

1 个答案:

答案 0 :(得分:0)

我会这样做:

import re

def _conv_num(match):
    return num2words(match.group())

def numbers_to_words(text):
    return re.sub(r'\b\d+\b', _conv_num, text)
  • 为清晰起见,导入整个正则表达式库并使用re.sub()而不只是sub
  • 如果你的转换函数采用匹配而不是字符串
  • ,则不需要lambda
  • 在正则表达式中使用单词边界匹配器(\b
  • 主要功能的更具描述性的名称
相关问题