值太多,无法解压缩lis列表

2024-10-03 15:31:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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版本的问题吗?你知道吗


Tags: toinimportforifmainresponsematch
1条回答
网友
1楼 · 发布于 2024-10-03 15:31:45

列表构造不正确-您有三个子列表,其中只有一个字符串,但它必须是一个子列表,其中有三个字符串

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( "" )

相关问题 更多 >