文章内容出现最多的单词(待完善)

这道题主要用来熟悉python的用法以及学会了分词和count;

同时在编译后发现总会出问题的原因就是‘be’在text里没有出现,无法删除。

def getText (text):
    text = text.lower()
    # 改为小写
    for ch in ",.;?-:\'":
        text = text.replace(ch, " ")
    # 将文本中的标点符号替换为空格
    return text
def wordFreq (text,topn):
    # text为待统计文本,topn表示取频率最高的单词个数
    words = text.split()
    # 将文本分词
    counts = {}
    for word in words:
        counts[word] = counts.get(word,0) + 1
        # 若该单词在字典中已经存在,则在原计数上加1,若该单词还未统计,则计数为1
    excludes = {'the','and','to','of','a','be'}
    # 定义集合存放需要去除的无意义单词
    for word in excludes:
        del(counts[word])
        # 在字典中删除无意义单词
    items = list(counts.items())
    # 将字典转换为列表,以方便排序
    items.sort(key=lambda x:x[1], reverse=True)
    # 按照单词频率计数的逆序排序
    return items[:topn]
# 返回出现频率前topn的单词和频率计数值


text='''Plastic surgery has always been a sensitive topic in China, with some people seeing it as a good thing, while
others see it as a scourge, and the debate between the two has been driving changes in people's attitudes.
At the beginning, plastic surgery was not recognized by people, mainly because of its low safety and not significant effect.
At the same time, many people still maintain the traditional concept of their parents' body, hair and skin, 
that it is not good to change their appearance by external means recklessly, so even if someone has undergone plastic surgery, 
they do not want others to know.
However, with the cultural exchange, the foreign concept of open and free pursuit of beauty is gradually introduced into China, 
and with the popularity of short video, people's pursuit of beauty has reached an unprecedented height. 
Also, with the progress of technology, the cost and risk of cosmetic surgery have greatly decreased and gradually gained more 
recognition in the form of medical beauty.'''

text = getText(text)
for word,freq in wordFreq(text,20):
    print("{:<10}{:>}".format(word,freq))
print('完成')

posted @ 2021-11-11 23:21  xuanxuan轩  阅读(245)  评论(0)    收藏  举报