python - 将句子中的所有数字单词翻译成数字
问题描述
我正在尝试用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
解决方案
要将多个生成的单词重新组合成一个字符串以传递给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)
这给您留下了翻译多字数字的问题。然而,在成功的单字翻译的情况下,您可以开始建立一个多字串来尝试翻译。
推荐阅读
- reactjs - TypeScript 2.8:在一次编译中执行和响应
- java - 我在这个条件语句中找不到逻辑错误。我不完全知道我的逻辑在哪里不正确
- php - display('string:'.$template_string) 不起作用
- android - 如何在不裁剪的情况下实现智能缩放的图像拼贴视图,如 Google Keep
- matlab - 如何返回包含给定数字的位置索引的行向量
- xml - 添加嵌套的 XML 元素
- css - Change the values of CSS variables at runtime in Typescript
- file - 通过网页从个人计算机共享文件(具有授权访问权限)
- java - 如何在 Spigot/Bukkit 插件中将门户重定向到正确的世界?
- python - 将一组 3 通道图像从 Python 读取到二维数组中以在 C 中使用的有效方法