在 python 中将数字转换为字符串中的单词

converting digits to word in string in python

> #!/usr/bin/env python
> 
> import inflect
> 
> p = inflect.engine() 
s1 = ''
> 
>         word = 'so do 1st or do 2nd or 3rd byte 4 th so do 5th longest word 3765 word 50 but 7th'
>     list_word = list(word)
>     print (list_word)
>     
>     for(m= 0; m <list_word.len(); m++):
>            if list_word[m].isalpha():
>                    s1 += i + ''
>            elif list_word[m].isnumeric():
>                    if (list_word[m+1].isnumeric()):
>                            continue
>                    elif (list_word[m+1]+list_word[m+2] == 'st'):
>                            s1 += first + ''
>                            m += 2
>                    elif (list_word[m+1]+list_word[m+2] == 'nd'):
>                            s1 += second + ''
>                            m += 2
>                    elif (list_word[m+1]+list_word[m+2] == 'rd'):
>                            s1 += third + ''
>                            m += 2
>                    elif (list_word[m+1]+list_word[m+2] == 'th'):
>                            if (list_word[m] == '5'):
>                                  s1 += fifth + ''
>                                  m += 2
>                            else :
>                                  s1 += p.number_to_words(list_word[m]) + ''
>                                  m += 2
>                    elif (list_word[m+1].isnumeric()):
>                            continue
>                    else:
>                            s1 += p.number_to_words(list_word[m]) + ''
>            else:
>                    s1 += ' '
> 

我需要将数字转换为单词,并制作一个仅包含字母的完整字符串。但问题是这种 for 循环 不能在 Python 中使用,我需要 迭代到在某些地方紧挨着下一个字符。请问我可以就此提出任何建议吗? 或者如果有人可以建议任何其他方法。

最简单的方法是改用 while 循环并手动迭代变量。例如:

m = 0
while m < len(list_word):
   body
   final else
      
   m += 1

实际上这与像您一样使用 for 循环是一样的

使用 num2words 包,我们可以做到这一点,无需任何 for 循环即可翻译整个字符串:

import re
import num2words

def transInt(num, mode=None):
    # Changes the mode of the translation to 
    # correctly translate ordinal numbers.
    if mode:
        mode = "ordinal"
    else:
        mode = "cardinal"

    # translates the number to either float
    # or int, so the translation works correctly.
    if "." in num:
        num = float(num)
    else:
        num = int(num)
    return num2words.num2words(num, to=mode)

def replaceInt(string):
    # Matches numbers, followed by optional ordinal-characters after it.
    return re.sub(r"(\d+\.*\d*)(st|nd|rd|th)*", lambda x: transInt(*x.groups()), string)

word = 'so do 1st or do 2nd or 3rd byte 4th so do 5th longest word 3765 word 50 but 7th'
print(word)
print(replaceInt(word))

输出:

so do 1st or do 2nd or 3rd byte 4th so do 5th longest word 3765 word 50 but 7th
so do first or do second or third byte fourth so do fifth longest word three thousand, seven hundred and sixty-five word fifty but seventh

翻译的重点是后缀(第 5 位中的“th”)与数字相连。在您的示例中,您有 "4 th" 不适用于我的代码。或者更确切地说,它将 4 翻译为 four 而不是 fourth