题目:

1、写一个程序,判断2008年是否是闰年。

2、写一个程序,用于计算2008年10月1日是这一年的第几天?(2008年1月1日是这一年的第一天)

3、(文件题)有一个“record.txt”的文件,内容如下:

# name, age, score

tom, 12, 86

Lee, 15, 99

Lucy, 11, 58

Joseph, 19, 56

第一栏为姓名(name),第二栏为年纪(age),第三栏为得分(score)

现在,写一个Python程序,

1)读取文件

2)打印如下结果:

得分低于60的人都有谁?

谁的名字以L开头?

所有人的总分是多少?

3)姓名的首字母需要大写,该record.txt是否符合此要求? 如何纠正错误的地方?

4、(练习正则表达式)有一个文件,文件名为output_1981.10.21.txt 。下面使用Python: 读取文件名中的日期时间信息,并找出这一天是周几。将文件改名为output_YYYY-MM-DD-W.txt (YYYY:四位的年,MM:两位的月份,DD:两位的日,W:一位的周几,并假设周一为一周第一天)

以下是程序清单:

 #-*-coding:utf-8 -*-

 # (1) judge leap year
def judge_leap_year(n):
# if n%4 == 0 and n%100 != 0:
# return True
# if n%100 == 0 and n%400 == 0:
if (n%4 == 0 and n%100 != 0) or (n%100 == 0 and n%400 == 0):
return True
else:
return False # ===================================================================
# (2) computing the sum days of any day(**.**.**)
def compute_year_counts(datestr):
# deal with these case:
# 2012.12.2
# 2012/12/2
# 2012-12-2
if datestr.find('.') > 0: date = datestr.split('.')
if datestr.find('/') > 0: date = datestr.split('/')
if datestr.find('-') > 0: date = datestr.split('-') year = int(date[0])
month = int(date[1])
day = int(date[2])
if (month < 1 or month > 12):
print "the error month!"
return -1
if (day > 31):
print "the error day!"
return -1 days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # nDays = 0
# i = 1
# while i < month:
# nDays += days[i-1]
# i = i + 1
nDays = sum(days[i] for i in range(0, month - 1))
if (judge_leap_year(year)):
nDays += 1
return nDays + day datestring = raw_input("input the datetime info:-->")
print compute_year_counts(datestring) # ===================================================================
# (3) read and write file: use class if perfect!
class UserProfier(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score def read_file_and_anlysis(filetext):
line_read = []
user_scores = []
has_invalid_name = False #the invalid name for line in filetext:
if not line.startswith('#') and len(line.strip()) != 0:
if line[0].islower():
line = line[0].upper() + line[1:]
has_invalid_name = True
cur = line.strip().split(', ')
user_scores.append(UserProfier(cur[0], int(cur[1]), int(cur[2])))
line_read.append(line)
# print the file
print "print the file"
for i in line_read:
print i
# statistic the score < 60
print "users whose score lower 60:"
for scores in filter(lambda s: s.score < 60 , user_scores):
print scores.name
# statistic the begin of name which is 'L'
print "users whose name's begin is 'L':"
for names in filter(lambda s: s.name.startswith('L'), user_scores):
print names.name
# statistic the total scores of all one
print "the total scores of everyone:"
allscores = map(lambda s:s.score, user_scores)
print allscores
print reduce(lambda x, y: x+y, allscores, 0) # open the file
with open("record.txt") as f:
read_file_and_anlysis(f) # ===================================================================
# (4) the useful example of regular expression
import os, re, datetime filename = "output_1981.10.21.txt" date_time = re.search("(?P<year>\d{4})\.(?P<month>\d{2})\.(?P<day>\d{2})\.", filename) year = date_time.group('year')
month = date_time.group('month')
day = date_time.group('day') print year, month, day
date = datetime.date(int(year), int(month), int(day))
w = date.weekday() + 1
W = str(w)
os.rename(filename, "output_"+year+'-'+month+'-'+day+'-'+str(w)+".txt")

python基础的几个小练习题的更多相关文章

  1. python基础语法学习常见小问题

    说明:我是最近觉得python在完成很多工作中方便使用而且功能强大,想突击学习一下.用的是廖雪峰老师的教程,学习python3.X.这里是廖雪峰老师的网站链接: http://www.liaoxuef ...

  2. 第2章 Python基础-字符编码&数据类型 综合 练习题

    1.转换 将字符串s = "alex"转换成列表 s = "alex" s_list = list(s) print(s_list) 将字符串s = " ...

  3. Python基础1:一些小知识汇总

    一.#!usr/bin/env python 脚本语言的第一行,指定执行脚本的解释器. #!/usr/bin/python 是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器 ...

  4. 【python基础语法】国庆扩展练习题

    ''' 一.国庆知识小拓展 1. 用户登陆程序需求: 1. 输入用户名和密码; 2. 判断用户名和密码是否正确? (name='root', password='123') 3. 为了防止暴力破解, ...

  5. python 基础之简单购物车小程序实现

    购物车 all_list = [ ('mac',9000), ('kindle',900), ('tesla',800), ('python',105), ('bile',2000), ] savin ...

  6. python基础day7_编码及小数据池

    数字概念,字符串----小数据池 数字的范围:-5---256 字符串: 1,不能有特殊字符 2,s*20还是同一个地址,s*21之后就是另外一个地址 i1 = 6 i2 = 6 print(id(i ...

  7. 第2章 Python基础-字符编码&数据类型 字典 练习题

    1.写代码,有如下字典,按照要求实现每一个功能,dic = {'k1':'v1','k2':'v2','k3':[11,22,33]} 请循环输出所有的 key dic = {'k1':'v1','k ...

  8. Python基础知识(六)------小数据池,集合,深浅拷贝

    Python基础知识(六)------小数据池,集合,深浅拷贝 一丶小数据池 什么是小数据池: ​ 小数据池就是python中一种提高效率的方式,固定数据类型使用同一个内存地址 代码块 : ​ 一个文 ...

  9. python基础语法、数据结构、字符编码、文件处理 练习题

    考试范围 '''1.python入门:编程语言相关概念2.python基础语法:变量.运算符.流程控制3.数据结构:数字.字符串.列表.元组.字典.集合4.字符编码5.文件处理''' 考试内容 1.简 ...

随机推荐

  1. php的pid文件指定用户

    比如pid文件指定www用户,首先得有这用户和用户组. 找到pathtophp-fpm.conf文件,修改里面得相关内容. 修改listen.owner=www listen.group=www us ...

  2. Android 二维码扫描/生成

    先看看实现效果 1.在module的build.gradle中执行compile操作 compile 'cn.yipianfengye.android:zxing-library:2.2' 2.在Ap ...

  3. 十字线阵---CBF,传统波束形成

    %传统波束形成,CBF (Ps:这个程序是别人的,不是我写的,但是具体是在哪里找到的已经忘了) clear all; close all; clc; %---------初始化常量---------- ...

  4. 8.24 关于valid.js

    这是昨天遇到的一个问题. js文件的validator函数里面套用了框架,但是页面上报错,说这不是一个函数..找了wd ht调都不知道怎么回事 后来jf哥说,是因为html页面没有引入valid.js ...

  5. Less入门及知识点整理

    LESS « 一种动态样式语言 文档链接:http://www.bootcss.com/p/lesscss/ 百科 Less 是一门 CSS 预处理语言,它扩充了 CSS 语言,增加了诸如变量.混合( ...

  6. Xadmin弹出窗口

    Xadmin弹出窗口 需求分析: 1.在添加页面的一对多和多对多字段后面加上+,点击+后,能显示出添加相应字段的窗口 2.提交后窗口关闭,添加的内容显示到当前页面 1.判断出当前字段是否为Foreig ...

  7. Python开发——函数【迭代器、生成器、三元表达式、列表解析】

    递归和迭代 小明问路篇解释说明 递归:小明——>小红——>小于——>小东:小东——>小于——>小红——>小明 小明向小红问路,因小红不知道,所以向小于问路,因小于不 ...

  8. Hadoop格式化namenode 出错 Error: A JNI error has occurred, please check your installation and try again Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/security/authorize/Refr

    一般是修改配置文件:etc/hadoop/hadoop-env.sh的时候出现的错误 export JAVA_HOME=/usr/jdk export HADOOP_COMMON_HOME=~/had ...

  9. if语句和三元运算符的替换

    要求: 已经知道两个数,计算最大值 两个整数,比较大小 使用if还是三元 判断条件多,使用if 三元,必须有结果的, if 可以没有结果的*/public class IfElseDemo_1{ pu ...

  10. Codeforces Round #436 (Div. 2)C. Bus 模拟

    C. Bus time limit per test: 2 seconds memory limit per test: 256 megabytes input: standard input out ...