import random
import re
requestResponseList = [
[r'.*to Paris ?(.*)',
["We apologise, but all our services to Paris {0} have been cancelled!"],
["We are sorry, but all our flights on {0} to Paris are fully booked!"],
["There are no available flights {0} to Paris! Please accept our apologies."]
]
]
def analyze(statement):
for pattern, responses in requestResponseList:
match = re.match(pattern, statement.rstrip(".!?"))
if match:
response = random.choice(responses)
if match.group(1):
return response.format(*[(match.group(1))])
return response.format(*[""])
def main():
statement = "What would be the first available flight to Paris next year?"
print(analyze(statement))
if __name__ == "__main__":
main()
这会返回太多值以解包(预期2)错误。谷歌搜索解决方案后,我更换了
for pattern, responses in requestResponseList :
用这个:
for pattern, responses in enumerate(requestResponseList):
这仍会产生错误:TypeError:第一个参数必须是字符串或编译模式。
奇怪的是,这个代码(枚举省略)一周前。这可能是Python版本的问题吗?
答案 0 :(得分:1)
列表构造不正确 - 您有三个内部包含单个字符串的子列表,但它必须是一个包含三个字符串的子列表
requestResponseList = [
[r'.*to Paris ?(.*)',
[
"We apologise, but all our services to Paris {0} have been cancelled!",
"We are sorry, but all our flights on {0} to Paris are fully booked!",
"There are no available flights {0} to Paris! Please accept our apologies."
]
]
]
现在它适用于我。
如果没有*[...]
*[...]
的原因
if match.group(1):
return response.format( match.group(1) )
return response.format( "" )