【问题标题】:Replace words by numbers in sentences [duplicate]用句子中的数字替换单词[重复]
【发布时间】:2021-07-23 05:05:36
【问题描述】:

我的句子中有时将数字写成单词,例如:

He takes classes of yoga two times per week.

我需要用数字替换写成单词的数字:

He takes classes of yoga 2 times per week.

如果是He takes classes of yoga twice per week.,则应保持原样。

我找到了一个名为 word2number 的库,可以将单词转换为数字 (link)。但是如何更新一个句子得到He takes classes of yoga 2 times per week.

from word2number import w2n

w2n.word_to_num('He takes classes of yoga two times per week.')
# output: 2

【问题讨论】:

  • @00:是的,但是我应该替换什么?我怎么知道two 是指2
  • 链接的 Stack Overflow 帖子中的解决方案已移植到 this library
  • 结束我的问题并提供“答案”链接的人:请仔细阅读问题。我问如何替换句子中的单词并返回句子。我没有问如何用数字替换任何孤立词。
  • @Fluxy 仔细阅读链接的答案:) 链接中有exact solution
  • @CoryKramer 如果“他每周上两次瑜伽课”会怎样?:)

标签: python


【解决方案1】:

这应该处理任意多字数。它不会处理句尾标点符号,例如“野兽的数量是六百六十六。”。你可能想先去掉标点符号。我想句子中间的逗号也会发生同样的情况。

def translate(sentence):
    result = []
    partial = []
    for word in sentence.split():
        partial.append(word)
        num = w2n.word_to_num(' '.join(partial))
        # If this worked, then go try to suck up another word.
        if num:
            continue
        # If there's more than one word in partial, then all but the
        # last make a successful number.
        if len(partial) > 1:
            result.append( w2n.word_to_num(' '.join(partial{[:-1]) ))
        result.append( word )
        partial = []
    return ' '.join(result)

【讨论】:

  • 对。对此没有解决方案,因为您无法判断他们想要 25 还是 20 5。大多数人会写“二十五”,但不可否认的是更大的数字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多