python简单示例

#coding:utf-8
import  random
import re
"""
设计一个简单的摇骰子的游戏,摇三次骰子猜大小(3~10为小,大于等于10小于18为大)
"""
#shark the dice three times
def 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 game
def 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 start
def 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  string

with 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:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值