ELIZA.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import re
  2. import random
  3. # 定义规则库:模式(正则表达式) -> 响应模板列表
  4. rules = {
  5. r'I need (.*)': [
  6. "Why do you need {0}?",
  7. "Would it really help you to get {0}?",
  8. "Are you sure you need {0}?"
  9. ],
  10. r'Why don\'t you (.*)\?': [
  11. "Do you really think I don't {0}?",
  12. "Perhaps eventually I will {0}.",
  13. "Do you really want me to {0}?"
  14. ],
  15. r'Why can\'t I (.*)\?': [
  16. "Do you think you should be able to {0}?",
  17. "If you could {0}, what would you do?",
  18. "I don't know -- why can't you {0}?"
  19. ],
  20. r'I am (.*)': [
  21. "Did you come to me because you are {0}?",
  22. "How long have you been {0}?",
  23. "How do you feel about being {0}?"
  24. ],
  25. r'.* mother .*': [
  26. "Tell me more about your mother.",
  27. "What was your relationship with your mother like?",
  28. "How do you feel about your mother?"
  29. ],
  30. r'.* father .*': [
  31. "Tell me more about your father.",
  32. "How did your father make you feel?",
  33. "What has your father taught you?"
  34. ],
  35. r'.*': [
  36. "Please tell me more.",
  37. "Let's change focus a bit... Tell me about your family.",
  38. "Can you elaborate on that?"
  39. ]
  40. }
  41. # 定义代词转换规则
  42. pronoun_swap = {
  43. "i": "you", "you": "i", "me": "you", "my": "your",
  44. "am": "are", "are": "am", "was": "were", "i'd": "you would",
  45. "i've": "you have", "i'll": "you will", "yours": "mine",
  46. "mine": "yours"
  47. }
  48. def swap_pronouns(phrase):
  49. """
  50. 对输入短语中的代词进行第一/第二人称转换
  51. """
  52. words = phrase.lower().split()
  53. swapped_words = [pronoun_swap.get(word, word) for word in words]
  54. return " ".join(swapped_words)
  55. def respond(user_input):
  56. """
  57. 根据规则库生成响应
  58. """
  59. for pattern, responses in rules.items():
  60. match = re.search(pattern, user_input, re.IGNORECASE)
  61. if match:
  62. # 捕获匹配到的部分
  63. captured_group = match.group(1) if match.groups() else ''
  64. # 进行代词转换
  65. swapped_group = swap_pronouns(captured_group)
  66. # 从模板中随机选择一个并格式化
  67. response = random.choice(responses).format(swapped_group)
  68. return response
  69. # 如果没有匹配任何特定规则,使用最后的通配符规则
  70. return random.choice(rules[r'.*'])
  71. # 主聊天循环
  72. if __name__ == '__main__':
  73. print("Therapist: Hello! How can I help you today?")
  74. while True:
  75. user_input = input("You: ")
  76. if user_input.lower() in ["quit", "exit", "bye"]:
  77. print("Therapist: Goodbye. It was nice talking to you.")
  78. break
  79. response = respond(user_input)
  80. print(f"Therapist: {response}")