python-3.x 不要更改引号内的时态

5ktev3wc  于 2022-12-15  发布在  Python
关注(0)|答案(1)|浏览(153)

我正在使用Tenseflow的change_tense方法将现在时更改为过去时。
但是双引号内的动词正在改变,它们应该保持不变。
示例:

  • 输入:Robin遇到问题时会对Alexa说“help”
  • 输出:Robin在遇到问题时对Alexa说“帮助”

这里的“帮助”不应改变。
我的代码:

import tenseflow

def get(self, request):
    response = {}
    sentance = request.data.get("sentance")
    if sentance:
        result = tenseflow.change_tense(sentance, "past")
        response["status_code"] = 200
        if result:
            response["past_tense"] = result
        return Response(response)

如有任何建议,欢迎提出,谢谢!

68bkxrlz

68bkxrlz1#

这是我的初步解决方案,我猜这不是最优的方法,但它解决了问题,欢迎任何评论,谢谢!

import re
from tenseflow import change_tense as tenseflow_change_tense

def change_tense(sentence, tense, ignore_doublequote_word=False):
    """Change the tense of the sentence to the specified tense except quoted words."""
    quoted_words = []
    if ignore_doublequote_word:
        quoted_words = re.findall(r'"([^"]*)"', sentence)
    changed_sentence = tenseflow_change_tense(sentence, tense)
    if quoted_words:
        for match in re.finditer(r'"([^"]*)"', changed_sentence):
            changed_sentence = changed_sentence.replace(match.group(0), f' "{quoted_words[0]}"')
            quoted_words.pop(0)
    return changed_sentence

相关问题