簡體   English   中英

如何從python中的字符串以word格式返回數字

[英]how to return numbers in word format from a string in 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']

瀏覽單詞列表並檢查每個單詞是否屬於一組數字單詞。 將相鄰單詞添加到臨時列表中。 當您找到一個非數字單詞時,創建一個新列表。 記住要說明句子開頭的非數字單詞和句子結尾的數字單詞。

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']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM