我有一个包含整数的字符串,我正在尝试找出如何将它们转换为单词(即 100 转换为一百)。我正在使用 inflect
包成功处理个别案例,但是我正在努力寻找正确的解决方案,使我能够保持句子原样,除了整数转换。
这是我目前拥有的:
mysent = ['this','is','1','of','my','sentences']
这就是我想要的结果:
mysent = ['this','is','one','of','my','sentences']
到目前为止,我已经尝试了以下方法,即删除除整数以外的所有单词。
import inflect
p = inflect.engine()
mysent = [p.number_to_words(token) for token in mysent if token.isdigit() is True]
我还尝试了以下我认为可能会解决问题的方法,但会产生语法错误:
mysent = [p.number_to_words(token) for token in mysent if token.isdigit() is True else token for token in mysent]
最佳答案
您可以使用 Python 的 ternary operator :
result = [p.number_to_words(token) if token.isdigit() else token for token in mysent]
print(result)
输出
['this', 'is', 'one', 'of', 'my', 'sentences']
关于python - 将字符串中的整数转换为列表理解中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58660736/