Python 2.7 删除标点符号,然后使用python计算每个单词出现的次数
大家好,我是python新手,需要编写一个程序来消除标点符号,然后计算字符串中的单词数。所以我有这个:Python 2.7 删除标点符号,然后使用python计算每个单词出现的次数,python-2.7,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)):
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)
问题是它会返回字母并计数,而不是我希望的单词。在这件事上你能帮我吗?去掉标点后
numberOfWords = len(txt.split(" "))
假设单词之间有一个空格
编辑:
工作原理
输出结果与海德罗的优秀答案相同,在去掉标点符号后,用单词键和每个单词的计数值来记录
numberOfWords = len(txt.split(" "))
假设单词之间有一个空格
编辑:
工作原理
>>> 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})
这个怎么样
>>> 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})
谢谢你的快速回复,但我需要计算每个单词的出现次数而不是总数谢谢你的快速回复,但我需要计算每个单词的出现次数而不是总数