- 论坛徽章:
- 0
|
这个题目挺有意思的呀,像个聊天机器人.
我写的(很粗糙):
- #coding:utf-8
- import fileinput, re,string
- regobj = re.compile(r'<\w+>')
- def replace(s,a):
- inter=regobj.finditer(s)
- if len(re.findall(r'<\w+>',s))>1:
- i=0
- for match in inter:
- s=string.replace(s,s[match.span()[0]:match.span()[1]],a[0][i])
- i=i+1
- else:
- for match in inter:
- s=string.replace(s,s[match.span()[0]:match.span()[1]],a[0])
- return s
- file=open('rules.txt','r')
- answer={}
- for i in file:
- answer[i.split('~')[0]]=i.split('~')[1]
- for i in answer.keys():
- answer[i]=[re.sub(regobj,r'(\w+)',i),answer[i]]
- file.close()
- while 1:
- inputstr=raw_input("You say:")
- for i in answer.keys():
- reg=answer[i][0]
- match = re.findall(reg, inputstr)
- if match:
- print replace(answer[i][1],match)
-
复制代码
运行:
You say:my name is two
You've already told me your name is two!
Hi there two!
You say:i feel happy
How often do you feel that way?
You say:you love me
What makes you think I love you?
You say:you hat me
What makes you think I hat you?
You say:you love sincerely me
What makes you think I love sincerely you? |
|