Python如何找到短语中的所有数字词?

2024-05-19 02:49:49 发布

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

我想知道你怎么可能在一个短语中发现所有的数字词。例如

math_str = "one times one plus sin(one hundred fifty three) minus three billion"
getNumberWords(math_str) #Returns one, one, one hundred fifty three, three billion

有正则表达式模式吗?你知道吗


Tags: 模式plus数字mathsinonereturnsthree
1条回答
网友
1楼 · 发布于 2024-05-19 02:49:49

这没有捷径,因为python不懂英语或人类语言,您需要有一个被视为数字单词的单词列表

math_str = "one times one plus sin(one hundred fifty three) minus three billion"
allowed = ['one', 'three', 'fifty', 'hundred', 'thousand', 'million', 'billion']

def getNumberWords(math_str):
    math_str = math_str.replace('(', ' ')
    math_str = math_str.replace(')', ' ')
    math_str = math_str.split()

    return [word for word in math_str if word in allowed]

print(getNumberWords(math_str))

在本例中,我只是输入了获得结果所需的字数,但如果希望结果准确,则需要填写大量的字数(数字)

相关问题 更多 >

    热门问题