首页 > 解决方案 > 将句子中的所有数字单词翻译成数字

问题描述

我正在尝试用python制作一个计算器,它可以用文字表达一个数学问题并解决它(例如——输入:16加27......输出:16 + 27)。现在我只是在把单词翻译成数字。我正在使用 w2n 库。我试图制作一个程序来计算句子中的单词,并为该数量的单词循环翻译过程。翻译过程是这样进行的:如果那个词是一个数字,那么就翻译它,如果不是,就让它保持原样。我的问题是,当我split()的字符串变成一个列表时,w2n 库无法翻译列表。我不知道如何解决这个问题。

from word2number import w2n

test_str = "What is sixteen plus twenty seven"  # creating a testable string

x = test_str.split()  # splitting the test string so I can count the words

num1 = 0  # these variables will isolate each word
num2 = 1

y = 1

while y <= len(x):  # while y is less than the number of words in the string, this will repeat
  try:
    res = w2n.word_to_num(str(x[num1:num2]))  # translate the isolated word
    print("The string after performing replace : " + str(res))  # print the translation
    num1 = num1 + 1  # isolate the next word
    num2 = num2 + 1
    y = y + 1  #  when y = the number of words in the sentence, the loop will stop

  except ValueError:
    print(str(x[num1:num2]))
    num1 = num1 + 1
    num2 = num2 + 1
    y = y + 1

标签: pythonmathtranslation

解决方案


要将多个生成的单词重新组合成一个字符串以传递给w2n,例如在您的拆分测试字符串中:

>>> words = 'What is sixteen plus twenty seven'.split()
>>> words
['What', 'is', 'sixteen', 'plus', 'twenty', 'seven']

你可以使用str.join如下:

>>> ' '.join(words[4:6])
'twenty seven'

您对单词列表的评论最好作为for循环处理:

for y, word in enumerate(x):  
  try:
    res = w2n.word_to_num(word)  # translate the single word
    print("The string after performing replace : " + str(res))  # print the translation

  except ValueError:
    print(word)

这给您留下了翻译多字数字的问题。然而,在成功的单字翻译的情况下,您可以开始建立一个多字串来尝试翻译。


推荐阅读