import urllib.request import urllib.parse import json import string import jieba import ssl import pytest def talk(keyword): target = r'http://api.qingyunke.com/api.php?key=free&appid=0&msg=' if keyword == "exit": return "不聊算了,拜拜" try: tmp = target + keyword url = urllib.parse.quote(tmp, safe=string.printable) # 创建 SSL 上下文 context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE with urllib.request.urlopen(url, context=context) as page: html = page.read().decode("utf-8") res = json.loads(html) content = res.get('content', '') if not content: return "没有获取到回复" # 分词处理 jieba.add_word('菲菲') words = jieba.cut(content, cut_all=False) answers = ''.join(['Friday' if word == '菲菲' else word for word in words]) # 替换特殊字符 answers = answers.replace('{br}', '\n').replace('"', '"') # 添加更多处理逻辑 answers = answers.replace('你好', '嗨') # 示例:将“你好”替换成“嗨” if '再见' in answers: answers = answers.replace('再见', '下次见!') # 示例:将“再见”替换成“下次见!” return answers except Exception as e: return f"发生错误: {str(e)}"