Python学习打卡--day26(基础练习:输入与输出)

"""
1-读取文件in.txt;
2-去掉标点符号,所有大写转为小写
3-合并相同的词,统计每个词出现的频率,并按照词频从大到小排序
4-将结果按行输出到文件out.txt
"""
import re


# 正则去标点和换行
def remove_punctuation(text):
    text = re.sub(r'[^\w ]', ' ', text)
    return text.strip().lower()


# 读文件,生成单词列表
with open('./in.txt', 'r') as file:
    data = file.read()
data = remove_punctuation(data)
data_list = data.split(' ')
print(data_list)

# 去除空白单词
data_list = filter(None, data_list)
print(data_list)
print(type(data_list))

# 生成单词和词频的字典
word_cnt = {}
for word in data_list:
    if word not in word_cnt:
        word_cnt[word] = 0
    word_cnt[word] += 1

# 按照词频排序
word_cnt = sorted(word_cnt.items(), key=lambda x: x[1], reverse=True)
print(word_cnt)

with open('./out.txt', 'w') as fp:
    for x, y in word_cnt:
        fp.write('{} {}\n'.format(x, y))
I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character. I have a dream today.

I have a dream that one day down in Alabama, with its vicious racists, . . . one day right there in Alabama little black boys and black girls will be able to join hands with little white boys and white girls as sisters and brothers. I have a dream today.

I have a dream that one day every valley shall be exalted, every hill and mountain shall be made low, the rough places will be made plain, and the crooked places will be made straight, and the glory of the Lord shall be revealed, and all flesh shall see it together.

This is our hope. . . With this faith we will be able to hew out of the mountain of despair a stone of hope. With this faith we will be able to transform the jangling discords of our nation into a beautiful symphony of brotherhood. With this faith we will be able to work together, to pray together, to struggle together, to go to jail together, to stand up for freedom together, knowing that we will be free one day. . . .

And when this happens, and when we allow freedom ring, when we let it ring from every village and every hamlet, from every state and every city, we will be able to speed up that day when all of God's children, black men and white men, Jews and Gentiles, Protestants and Catholics, will be able to join hands and sing in the words of the old Negro spiritual: "Free at last! Free at last! Thank God Almighty, we are free at last!"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值