1

大家好,我是 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)

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

4

2 回答 2

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})
于 2013-03-07T09:22:38.873 回答
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

输出与 Haidro 的优秀答案相同,一个带有单词键和每个单词计数值的字典

于 2013-03-07T09:00:15.973 回答