$ cat baidu_qa.py
#!/usr/bin/python
# encoding: utf-8
import re
collector = {}
patt = re.compile(r"\w+")
def loopgetter(prompt, quitflag):
while True:
gotter = raw_input(prompt)
if not gotter:
continue
if gotter == quitflag:
raise StopIteration
yield gotter
for ln in loopgetter(prompt="? ", quitflag="stop"):
for word in patt.findall(ln):
collector[word] = collector.get(word, 0) + 1
for word in loopgetter(
prompt="Enter your search word:",
quitflag="stop"):
print "%s occurs %d times." % (
word,
collector.get(word, 0)
)
$ python baidu_qa.py
? i have a car and a big house
? i am a teacher
? i love you too much
? that we shoud do this
? stop
Enter your search word:and
and occurs 1 times.
Enter your search word:i
i occurs 3 times.
Enter your search word:stop
$
追问您这个写的太高级了。。
我只是个初学者, 用python3.2的版本。。。
有没有简洁一些的呢!
追答#!/usr/bin/python
# encoding: utf-8
collector = {}
STOPFLAG = "stop"
while True:
gotter = raw_input("? ")
if gotter == STOPFLAG:
break
for word in gotter.split(" "):
collector[word] = collector.get(word, 0) + 1
while True:
q = raw_input("Enter your search word:")
if q == STOPFLAG:
break
print "%s occurs %d times." % (
q,
collector.get(q, 0)
)
追问您的这个代码不适用于python 3.3.2
追答$ python3 baidu_qa.py
? i have a car and a big house
? i am a teacher
? i love you so much
? that we shoud do this
? stop
Enter your search word:i
i occurs 3 times.
Enter your search word:and
and occurs 1 times.
Enter your search word:stop
$ cat baidu_qa.py
#!/usr/bin/python3
# encoding: utf-8
collector = {}
STOPFLAG = "stop"
while True:
gotter = input("? ")
if gotter == STOPFLAG:
break
for word in gotter.split(" "):
collector[word] = collector.get(word, 0) + 1
while True:
q = input("Enter your search word:")
if q == STOPFLAG:
break
print("%s occurs %d times." % (
q,
collector.get(q, 0)
))
$
本回答被提问者和网友采纳