删除标点符号,然后使用python计算每个单词出现次数

时间:2013-03-07 08:56:10

标签: python-2.7

大家好我是python的新手,需要编写程序来消除标点符号,然后计算字符串中的单词数。所以我有这个:

import sys
import string
def removepun(txt):
    for punct in string.punctuation:
        txt = txt.replace(punct,"")
        print txt
        mywords = {}
        for i in range(len(txt)):
            item = txt[i]
            count = txt.count(item)
            mywords[item] = count
    return sorted(mywords.items(), key = lambda item: item[1], reverse=True)

问题是它返回字母并计算它们而不是我所希望的单词。你能帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

这个怎么样?

>>> import string
>>> from collections import Counter
>>> s = 'One, two; three! four: five. six@#$,.!'
>>> occurrence = Counter(s.translate(None, string.punctuation).split())
>>> print occurrence
Counter({'six': 1, 'three': 1, 'two': 1, 'four': 1, 'five': 1, 'One': 1})

答案 1 :(得分:0)

删除标点后

numberOfWords = len(txt.split(" "))

假设单词之间有一个空格

编辑:

a={}
for w in txt.split(" "):
   if w in a:
     a[w] += 1
   else:
     a[w] = 1

如何运作

  1. a设为dict
  2. 迭代了txt中的单词
  3. 如果已有dict a [w]的条目,则添加一个
  4. 如果没有条目,则设置一个,初始化为1
  5. 输出与Haidro的优秀答案相同,是一个带有单词键和每个单词计数值的词典