【问题标题】:How to produce a positive or negative response based on one regex?如何根据一个正则表达式产生积极或消极的回应?
【发布时间】:2021-06-29 03:21:56
【问题描述】:

所以我正在编写一个 python 机器人,它会根据用户输入中的一些关键词来响应用户输入。我的程序接受西班牙语输入并显示西班牙语输出。它们是非常简单的短语。如果输入是“Yo no estoy feliz”,意思是“我不开心”,那么预期的输出应该是“¿Porqué no estás feliz?”,意思是“你为什么不开心”。如果输入是“Yo estoy feliz”,意思是“我很高兴”,那么预期的输出应该是“¿Porqué estás feliz?”。

我可以用两种不同的正则表达式来处理正面和负面的情况,但我试图用一个正则表达式来处理。我尝试使用可选分组来实现这一点,但如果我的输入是“Yo estoy feliz”,我没有得到想要的结果。但是,我通过“Yo no estoy feliz”得到了想要的结果。我对正则表达式非常陌生,我将不胜感激任何有关这方面的指导。下面是代码和一些cmets

import sys
import re

# Run from command line as: python [progname.py] "Yo no estoy feliz."

# INPUT:            Yo no estoy feliz.     [I am not happy]
# EXPECTED OUTPUT : ¿Porqué no estás feliz?     [Why are you not happy]

###### Translation #######
# ¿Porqué no estás feliz? == Why are you not happy?
# ¿Porqué estás feliz? == Why are you happy

def caseHandler(regExInput):
    return re.compile(regExInput, re.IGNORECASE)

def bot(userInput):
    reply = ""

    expression = caseHandler(r'(.* )?(?:no)? estoy (.* )?(.+)\b')


    if (expression.match(userInput)):
        groupName = expression.search(userInput)    # Ensures if input matches regex
        if (groupName.group(4) and groupName.group(2)):
            reply = "¿Porqué no estás " + groupName.group(4) + "?" # presence of "no" in input
        elif (groupName.group(4)):
            reply = "¿Porqué estás " + groupName.group(4) + "?" # absence of "no" in INPUT
        else:
            reply = "Cuéntame más."  # Tell me more

    else:
        reply = "Cuéntame más."  # Tell me more

    return reply

if (len(sys.argv) < 2):
    print("Please provide an input phrase")

else:
    print(bot(str(sys.argv[1])))


【问题讨论】:

  • 如果您只是在句子中寻找no 来做出决定,您可以使用if 'no' in user_input。否则你可能会搜索re.match(pattern, user_input)
  • @PeppermintPaddy 抱歉,您能详细说明一下吗?

标签: python regex chatbot re


【解决方案1】:

你可以试试这样的:

import sys;
import re;

def caseHandler(regExInput):
    return re.compile(regExInput, re.IGNORECASE)

def bot(userInput):
    expression = caseHandler(r'((?:\bno )?)estoy +(.+)\b')
    m = expression.search(userInput)
    if m:
        reply = "¿Porqué " + m.group(1) + "estás " + m.group(2) + "?"
    else:
        reply = "Cuéntame más." 

    return reply

if (len(sys.argv) < 2):
    print("Please provide an input phrase")

else:
    print(bot(str(sys.argv[1])))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多