如何从python中的字符串返回word格式的数字

2024-05-12 19:22:45 发布

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

编辑:“已经回答”不是在说我是什么。我的字符串已经是word格式了。我要把那些词从我的字串里删掉,列成一个单子

我正在尝试在python中为语音助手处理短语。你知道吗

当我说这样的话:

"What is 15,276 divided by 5?"

它的格式如下:

"what is fifteen thousand two hundred seventy six divided by five"

我已经有了一种方法,可以把一个字符串变成一个int,那么有没有一种方法可以从这个短语中得到这样一个列表呢?你知道吗

['fifteen thousand two hundred seventy six','five']

Tags: 方法字符串编辑byis格式wordfive
1条回答
网友
1楼 · 发布于 2024-05-12 19:22:45

浏览单词列表,检查每个单词是否属于一组数字单词。将相邻单词添加到临时列表中。当你找到一个非数字单词时,创建一个新的列表。记住在句首要说明非数字词,在句尾要说明数字词。你知道吗

result = []
group = []
nums = set('one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty thirty forty fifty sixty seventy eighty ninety hundred thousand million billion trillion quadrillion quintillion'.split())
for word in "what is fifteen thousand two hundred seventy six divided by five".split():
    if word in nums:
        group.append(word)
    else:
        if group:
            result.append(group)
        group = []

if group:
    result.append(group)

结果:

>>> result
[['fifteen', 'thousand', 'two', 'hundred', 'seventy', 'six'], ['five']]

要将每个子列表合并为一个字符串,请执行以下操作:

>>> list(map(' '.join, result))
['fifteen thousand two hundred seventy six', 'five']

相关问题 更多 >