删除标点符号然后使用python计算每个单词出现的次数 [英] removing punctuation then counting the no of every word occurance using python

查看:37
本文介绍了删除标点符号然后使用python计算每个单词出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

导入系统导入字符串def removepun(txt):对于 string.punctuation 中的 punct:txt = txt.replace(punct,"")打印txt我的话 = {}对于我在范围内(len(txt)):项目 = txt[i]计数 = txt.count(item)mywords[item] = 计数返回排序(mywords.items(), key = lambda item: item[1], reverse=True)

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

解决方案

这个怎么样?

<预><代码>>>>导入字符串>>>从集合导入计数器>>>s = '一、二;三!四五.六个@#$,.!'>>>出现 = Counter(s.translate(None, string.punctuation).split())>>>打印事件计数器({'六':1,'三':1,'二':1,'四':1,'五':1,'一':1})

Hello everybody I am new to python and need to write a program to eliminate punctuation then count the number of words in a string. So I have this:

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)

The problem is it returns back letters and counts them and not words as I hoped. Can you help me in this matter?

解决方案

How about this?

>>> 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})

这篇关于删除标点符号然后使用python计算每个单词出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆