python简单示例

来源:互联网 发布:tcp和udp端口号区别 编辑:程序博客网 时间:2024/05/29 12:09
#coding:utf-8import  randomimport re"""设计一个简单的摇骰子的游戏,摇三次骰子猜大小(3~10为小,大于等于10小于18为大)"""#shark the dice three timesdef get_list_of_dice(number =3,points =None):    print('Start Rolling the dice:')    if points ==None:        points = []    while number >0:        point = random.randrange(1,7)        points.append(point)        number = number -1    return points#get  the result of the gamedef get_game_result(total):    isSmall = 3<=total<10    isBig = 10<=total<18    if isSmall:        print('The result is:Small')        return 'Small'    elif isBig :        print('The result is:Big')        return 'Big'#game startdef Start_game():    guess =input('please guess  the result of Big or Small:')    print(guess)    list =get_list_of_dice()    total  = sum(list)    result = get_game_result(total)    print(result)    if result == guess:        print('Congratulation to you! You are Right!')    else:        print('Sorry ,You are wrong!')Start_game()"""正则表达式匹配电话号码和邮箱"""#re正则表达式匹配电话号码和邮箱# 正则匹配电话号码phone = "13893670000"p2 = re.compile('^0\d{2,3}\d{7,8}$|^1[358]\d{9}$|^147\d{8}')phonematch = p2.match(phone)if phonematch:    print(phonematch.group())else:    print("phone number is error!")# 正则匹配邮箱和电话号码emailorphone = "aaaaaaaaaa888@sina.cn"p3 = re.compile('^0\d{2,3}\d{7,8}$|^1[358]\d{9}$|^147\d{8}|[^\._-][\w\.-]+@(?:[A-Za-z0-9]+\.)+[A-Za-z]+')emailorphonematch = p3.match(emailorphone)if emailorphone:    print(emailorphonematch.group())else:    print("phone or email error...")"""对文件内的词汇进行词频统计
文件:
"""#词频统计path = '/Users/cykj/DeskTop/caoyajun/python/walden.txt'with open(path,'r') as text:    words = text.read().split()    print(words)    for word in words:        print('{}--{} times'.format(word,words.count(word)))"""存在问题:1。带标点符号的单词也被统计在内         2。Python对大小写敏感,统计区分了大小写"""#改进后import  stringwith open(path,'r') as text:    wods = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()];#string.punctuation标点符号    words_index = set(wods)    counts_dict = {index:wods.count(index) for index in words_index}for word in sorted(counts_dict.items(),key=lambda x: counts_dict[x],reverse=True):    print('{} -- {} times'.format(word,counts_dict[word]))
result: