在Python中解析字符串输入的更好方法?
我正在制作一个机器人,它将根据用户输入(字符串)输出不同的信息。我想知道是否有更好的方法来解析输入并重定向到不同的结果:在Python中解析字符串输入的更好方法?,python,regex,Python,Regex,我正在制作一个机器人,它将根据用户输入(字符串)输出不同的信息。我想知道是否有更好的方法来解析输入并重定向到不同的结果: def query(msg: str): if re.compile(r"moci(o|ó)?n(es)? de (procedimiento)s?", re.IGNORECASE).search(msg): return open("mociones/mocion_procedimiento.txt", "r").read() elif r
def query(msg: str):
if re.compile(r"moci(o|ó)?n(es)? de (procedimiento)s?", re.IGNORECASE).search(msg):
return open("mociones/mocion_procedimiento.txt", "r").read()
elif re.compile(r"moci(o|ó)?n(es)? de (ó|o)?rden(es)?", re.IGNORECASE).search(msg):
return open("mociones/mocion_orden.txt", "r").read()
elif re.compile(r"moci(o|ó)?n(es)? de duda(s)?", re.IGNORECASE).search(msg):
return open("mociones/mocion_duda.txt", "r").read()
elif re.compile(r"moci(o|ó)?n(es)? de privilegio(s)?", re.IGNORECASE).search(msg):
return open("mociones/mocion_privilegio.txt", "r").read()
...
elif re.compile(r"defender (el|los)? anteproyectos?", re.IGNORECASE).search(msg):
return open("debate_particular/index.txt", "r").read()
elif re.compile(r"anteproyectos?", re.IGNORECASE).search(msg):
return open("anteproyecto/index.txt", "r").read()
else:
return "_*ERROR*_\n\nNo search results were found for \n`{query}`".format(query=msg)
一个明显的建议是使用dict
regex=>path
并使用循环,而不是一堆if
语句:
paths = {
r"(?i)moci[oó]?n(es)? de (procedimiento)s?": "mociones/mocion_procedimiento.txt",
r"(?i)moci[oó]?n(es)? de [óo]?rden(es)?": "mociones/mocion_orden.txt"
}
def path_for_msg(msg):
for r, p in paths.items():
if re.search(r, msg):
return p
此外,几乎不需要re.compile
,因为re
负责幕后编译
如果顺序很重要,则适当的数据结构是元组列表:
paths = [
(r"(?i)moci[oó]?n(es)? de (procedimiento)s?", "mociones/mocion_procedimiento.txt"),
(r"(?i)moci[oó]?n(es)? de [óo]?rden(es)?", "mociones/mocion_orden.txt")
}
def path_for_msg(msg):
for r, p in paths:
if re.search(r, msg):
return p
一个明显的建议是使用dict
regex=>path
并使用循环,而不是一堆if
语句:
paths = {
r"(?i)moci[oó]?n(es)? de (procedimiento)s?": "mociones/mocion_procedimiento.txt",
r"(?i)moci[oó]?n(es)? de [óo]?rden(es)?": "mociones/mocion_orden.txt"
}
def path_for_msg(msg):
for r, p in paths.items():
if re.search(r, msg):
return p
此外,几乎不需要re.compile
,因为re
负责幕后编译
如果顺序很重要,则适当的数据结构是元组列表:
paths = [
(r"(?i)moci[oó]?n(es)? de (procedimiento)s?", "mociones/mocion_procedimiento.txt"),
(r"(?i)moci[oó]?n(es)? de [óo]?rden(es)?", "mociones/mocion_orden.txt")
}
def path_for_msg(msg):
for r, p in paths:
if re.search(r, msg):
return p
另一种方法是采用更面向对象的方法,创建单独的类来处理不同类型的输入,并将它们安排到一个责任链中——类似于georg的建议,只是您将迭代消息处理程序对象而不是原始正则表达式模式
有关更多详细信息,请参阅。另一种方法是采用更面向对象的方法,创建单独的类来处理不同类型的输入,并将它们安排到责任链中-类似于georg的建议,只是您将迭代消息处理程序对象而不是原始正则表达式模式
有关更多详细信息,请参阅。“更好”如何实现?如果这是您认为可以改进的工作代码,请查看。另外,请注意,通过每次调用函数时显式地重新编译正则表达式,可能比根本不编译它们效率要低;要从编译中获益,请将其移出函数。“更好”如何?如果这是您认为可以改进的工作代码,请查看。另外,请注意,通过每次调用函数时显式地重新编译正则表达式,可能比根本不编译它们效率要低;若要从编译中获益,请将其移到函数之外。但有什么方法可以保证顺序吗?这似乎完全忽略了它。。。秩序很重要,但我有没有办法维持秩序?这似乎完全忽略了它。。。秩序很重要