文本文档中不包括标点符号的词频

2024-05-18 22:29:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个程序,它将读取一个名为“,”的文本文档中的所有单词玻璃狗.txt". 一旦程序读取单词,它将需要删除所有的标点,以及,使所有的字母小写。然后当程序完成所有这些,我希望它打印它找到的单词,以及它在文档中被使用了多少次。在

以下是我目前为止的代码:

def run():
    count = {} 
    for w in open('GlassDog.txt').read().split(): 
        if w in count: 
            count[w] += 1 
        else: 
            count[w] = 1

    for word, times in count.items(): 
        print ("%s was found %d times" % (word, times)) 

run()

此代码将读取并显示单词和单词的频率。但是,我无法找到一种方法来实现一个代码,即删除标点并用小写字母替换大写字母。这个问题可能已经被问过几次了,我只是似乎找不到任何东西能满足我的需求。如果这是一个重复的问题,我很抱歉。在


Tags: run代码in程序txtforcount字母
3条回答

您可以在字符串上使用user.lower()将其转换为if块之前的小写形式,如果只匹配字母数字,请尝试使用正则表达式,具体看\w

from collections import Counter

def just_alnum(s):
    return ''.join(c for c in s if c.isalnum())

with open('GlassDog.txt', 'r') as f:
    counts = Counter(just_alnum(w.lower()) for w in f.read().split())
>>>msg = "Hello,World!"
>>>msg = msg.lower() #convert into all lowercase
>>>print msg
hello,world!
>>>msg = filter(lambda x: x.isalpha(), msg) #remove every character that isn't a letter
>>>print msg
helloworld

相关问题 更多 >

    热门问题