Python 学习——每天写点小东西-2

2016-06-16  本文已影响0人  盐巴有点咸

题目来源: github-Yixiaohan

1.使用python生成200个优惠码

import string
import random


key_len = 20
key_num = 200
base_string = string.ascii_letters + string.digitsdef 


get_key():    
    key_list = []    
    for _ in range(key_len):        
        key_list.append(random.choice(base_string))    
        return ''.join(key_list)

def print_key(num):    
    for _ in range(num):        
        key_code = get_key()        
        print(key_code)

print_key(key_num)

2.任一个英文的纯文本文件,统计其中的单词出现的个数。

from collections import Counter
import re

def create_list(path):    
    with open(path, 'r') as file:        
        data_list = []        
        for line in file:            
            content = re.sub("\"|,|\.", '', line)  #替换" , . 为空格
            data_list.extend(content.strip().split(' '))    
    return data_list

def count(path):    
    data = create_list(path)    
    return Counter(data)

if __name__ == '__main__':    
    file_path = 'duanzi.txt'    
    print(count(file_path))

结果:

Counter({'the': 5, 'and': 3, 'provinces': 2, 'to': 2, 'China': 1, 'credit': 1, 'said': 1, 'Bank': 1, 'Shandong': 1, 'are': 1, 'Chongqing': 1, 'as': 1, 'bank': 1, 'last': 1, 'by': 1, 'central': 1, 'rated': 1, 'will': 1, 'latest': 1, 'you': 1, 'program': 1, 'was': 1, 'six': 1, 'economy': 1, 'high-quality': 1, 'assets': 1, 'refinance': 1, 'of': 1, 'in': 1, 'move': 1, 'year': 1, 'allow': 1, 'municipalities': 1, 'banks': 1, 'Shanghai': 1, "People's": 1, 'Beijing': 1, 'In': 1, 'Guangdong': 1, 'introduced': 1, 'other': 1, 'support': 1, 'who': 1, 'first': 1})

都是很简单的小程序,只为督促自己坚持写下去

上一篇 下一篇

猜你喜欢

热点阅读