test_qa.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import urllib.request
  2. import urllib.parse
  3. import json
  4. import string
  5. import jieba
  6. import ssl
  7. import pytest
  8. def talk(keyword):
  9. target = r'http://api.qingyunke.com/api.php?key=free&appid=0&msg='
  10. if keyword == "exit":
  11. return "不聊算了,拜拜"
  12. try:
  13. tmp = target + keyword
  14. url = urllib.parse.quote(tmp, safe=string.printable)
  15. # 创建 SSL 上下文
  16. context = ssl.create_default_context()
  17. context.check_hostname = False
  18. context.verify_mode = ssl.CERT_NONE
  19. with urllib.request.urlopen(url, context=context) as page:
  20. html = page.read().decode("utf-8")
  21. res = json.loads(html)
  22. content = res.get('content', '')
  23. if not content:
  24. return "没有获取到回复"
  25. # 分词处理
  26. jieba.add_word('菲菲')
  27. words = jieba.cut(content, cut_all=False)
  28. answers = ''.join(['Friday' if word == '菲菲' else word for word in words])
  29. # 替换特殊字符
  30. answers = answers.replace('{br}', '\n').replace('"', '"')
  31. # 添加更多处理逻辑
  32. answers = answers.replace('你好', '嗨') # 示例:将“你好”替换成“嗨”
  33. if '再见' in answers:
  34. answers = answers.replace('再见', '下次见!') # 示例:将“再见”替换成“下次见!”
  35. return answers
  36. except Exception as e:
  37. return f"发生错误: {str(e)}"