python 可以统计出 一个词的出现的次数的代码

输入句子
然后输入 关键字
输出 显示 关键字 出现的次数

这里有个例子:
? 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 ( 当输入stop 这个代码将结束)
如何实现这个功能请大侠解答!!!!!万分感激!
目前代码我只写到了 wordList

但不知道如何从 wordList 中搜索出 searchWord 的 数量!
sentence='holder'
wordList=[]

while sentence!='stop':
sentence=input("?")
wordList.append(sentence)
if sentence=='stop':
sentence=sentence.lower()
wordList.remove("stop")

wordCount=0
result=0
while searchWord!='stop':
searchWord=input("Enter your search word")
words=wordList[wordCount] (从这里开始真不知道该如何写了)
words_split=words.split(sep=" ")

先用split()将输入切分成一个列表,获得列表data
然后用列表统计函数data.count('aa') 就能统计出有多少个aa
具体自己写写吧。
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-03-30
$ 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)
        ))
$

本回答被提问者和网友采纳
第2个回答  2013-11-22
mapreduce
相似回答