我有一個包含普通數字和序數的句子,我想將序數數字轉換為像 2 nd 到 Second、56 th 到 50th Six 這樣的單詞。我使用了庫 num2words 和下面的代碼完美地作業。
import num2words
text = "ordinal numbers are like as 42 nd, 67 th, and 5 th and plain numbers such as 1, 2, 3."
numbers = re.findall('(\d )[st|nd|rd|th]', text)
numbers
for n in numbers:
ordinalAsString = num2words.num2words(n, ordinal=True)
print(ordinalAsString)
#forty-second
#sixty-seventh
#fifth
現在我想創建一個 lambda 函式,這樣,
sentence = "ordinal numbers are like as 42 nd, 67 th, and 5 th and plain numbers such as 1, 2, 3."
o/p sentence = "ordinal numbers are like as fourty-second, sixty-seventh, and fifth and plain numbers such as 1, 2, 3."
我寫了這樣的函式,
sentence = re.sub(r"(\d )[st|nd|rd|th]", lambda x: num2words.num2words(str(x), ordinal=True), sentence)
但這會引發錯誤,例如,
InvalidOperation: [<class 'decimal.ConversionSyntax'>]
代碼有什么問題?
uj5u.com熱心網友回復:
有兩個問題:
您的正則運算式未正確匹配后綴,僅匹配后綴的第一個字母。
[st|nd|rd|th]與括號內的字符完全匹配;重復項將被忽略,因此它等效于[st|ndrh], 將|視為一個字符來匹配每個字母。使用r"(\d )(?:st|nd|rd|th)"代替; 的|非捕獲組內(?:...)不作業的4個圖案分離st,nd,rd,和th。傳遞給的可呼叫物件
re.sub將一個Match物件作為其引數。您需要使用它的group方法來提取捕獲的刺。lambda x: num2words.num2words(x.group(1), ordinal=True).
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/348431.html
