我正在创建一个将通过字符串列的函数。有些字符串中有数字,有些字符串中没有数字。如果一个字符串包含一个数字,我想将该数字更改为文本版本(即'I was on hold for 20分钟'到'I was on hold for 20分钟')
这是我到目前为止所做的,但我认为isdigit()正在查看整个字符串,而不是字符串中的令牌。
import inflect
def int_to_word(words):
p = inflect.engine()
new_words = []
for word in words:
if word.isdigit():
new_word = p.number_to_words(word)
new_words.append(new_word)
else:
new_words.append(word)
return new_words
这完全取决于您传递给int_to_words
的输入,而您的问题中没有包含这些输入。
输入:string
您需要将字符串拆分为一个列表,该列表由空格分隔。这样可以确保遍历整个数字,而不是字符串中的单个字符。
def int_to_word(words):
p = inflect.engine()
new_words = []
for word in words.split():
if word.isdigit():
new_words.append(p.number_to_words(word))
else:
new_words.append(word)
return ' '.join(new_words)
print(int_to_word('I was on hold for 20 minutes'))
#I was on hold for twenty minutes
Input:list
对于一个句子列表,您将需要添加一个额外的迭代。
def int_to_word(words):
p = inflect.engine()
result = []
for element in words:
new_words = []
for word in element.split():
if word.isdigit():
new_words.append(p.number_to_words(word)
)
else:
new_words.append(word)
result.append(' '.join(new_words))
return result
print(int_to_word(['I was on hold for 20 minutes', '1 2 3']))
#['I was on hold for twenty minutes', 'one two three']