Python语言程序设计:Lab4
Programming
1.Analysing a Text File
Look at the file xian_info.txt which is like this:
Xi'an
China
8705600
Northwest Chang'an Shaanxi_Normal Xidian
34 16 N 108 54 E
3 3 8 15 20 25 26 25 20 15 8 2
First line is a country. Second line integer is a population. Third line is serveral words, each a
university, all one one line. Fourth line is a latitude and longitude; it is INTEGER INTEGER 'N'/'S'
INTEGER INTEGER 'E'/'W'. Fifth line is series of temperatures, one for each month.
Your task is to extract all this information into a dictionary as follows:
xian_info = { 'country': 'China', 'population': 8705600,\
'universities': [ 'Northwest', 'Chang\'an', 'Shaanxi Normal',\
'Xidian' ],\
'location': ( 34, 16, 'N', 108, 54, 'E' ),\
'temperature': [ 3, 3, 8, 15, 20, 25, 26, 25, 20, 15, 8, 2 ] }
How to do it:
1. You need a top-level function process_text(). It will return a dictionary like the above.
It should have local variables:
lines = []
country = ''
population = 0
universities = []
location = ()
temperature = []
info = {}
It does the following in order:
lines = read_file_lines()
- returns a list of strings (see previous lab)
- you need to define this function
access the country in the list lines - it is the first element and already it is a string.
Set variable population to the population which is on the second line of the list lines. You need to
convert it to an integer using a type case.
Universities are on the third line of the list lines. Write a function get_universities() which takes as
argument a string and which returns as a result a list of universities. The third line of the file is a
string. Your function need to take this string as argument and convert it to a list of strings, one for
each university. Conveniently, these are separated by spaces. Remember you can do something like:
'a b c'.split(' ')
which gives a list of words:
[ 'a', 'b', 'c' ]
NB: ' ' is one space and it is the separator.
Use your function get_universities() to set the local variable universities to the resulting list of words.
Now write a similar function get_location() which takes as arg a string, tokenises using .split and then
extracts the parts of the Lat/Long position. The result always has six elements.
Next, write a function get_temperatures() which takes as arg a string and returns a list of integers
containing the temperatures for the different months. Remember, .split( ' ' ) will return a list of strings.
You need to convert these to integers using int().
Finally, you need to set result to a dictionary containing all the data. You have already collected it in
the local variables.
At the end you return info:
return( info )
Develop process_text() by stages, one function at a time. Test each as you go along.
'''process_text.py''' #读文件
def read_file_line(filename):
f=open(filename,encoding='utf-8')
lines=[]
#lines=f.readlines()
for line in f.readlines():
line=line.strip('\n')
lines.append(line)
#print(lines)
return lines
#获取大学
def get_universies(info):
return info.split(' ')
#获取地址
def get_location(location):
return location.split(' ')
#获取温度
def get_temperature(temperature):
return temperature.split(' ') #此方法是总方法,调用上述四个函数,用于处理文本
def process_text(filename):
lines = []
country = ''
population = 0
universities = []
location = ()
temperature = []
info = {} lines=read_file_line(filename)
#print(lines)
country=lines[0]
#print(country)
population=int(lines[1])
#print(population)
universities=get_universies(lines[2])
#print(universities)
location=get_location(lines[3])
#print(location)
temperature=get_location(lines[4])
#print(temperature) info={'country':country,'population':population,'universities':universities,'location':location,'temperature':temperature}
return info
'''test.py'''
from process_text import * info=process_text('xian_info.txt')
print(info)
2 Changing a Binary File
Earlier, you used read_write_binary_files.py to make an exact copy of a binary file and to use
different buffer sizes.
Now we will actually alter the image. We will now use it_building.bmp (NB: .bmp not .jpg). Write a
program to:
1. Open a file as binary and read the contents into a bytearray. If you open the file as file, you can
do it like this:
data = bytearray( file.read() )
2. Open a new binary file for writing.
3. The first 54 bytes contain header information in a .bmp. Write those to the file unchanged.
4. All the remaining bytes, if the value of the byte is less than 200, add 40 to the binary value. Then
write out the byte. You need to convert the data to a byte like this (in this example just byte number
100):
file.write( ( data[ 100 ] + 40 ).to_bytes( 1, byteorder='big' ) )
5. Close the file.
Take a look at the resulting picture; it will have changed.
"""changeBinaryFile.py"""
f=open('it_building.bmp',"rb+")
data=bytearray(f.read()) print(data[:54])
for i in range(0,len(data)):
if int(data[i])<200:
f.write( ( data[i] +40 ).to_bytes( 1, byteorder='big' ) )
Python语言程序设计:Lab4的更多相关文章
- 【任务】Python语言程序设计.MOOC学习
[博客导航] [Python导航] 任务 18年11月29日开始,通过9周时间跨度,投入约50小时时间,在19年1月25日之前,完成中国大学MOOC平台上的<Python语言程序设计>课程 ...
- 全国计算机等级考试二级Python语言程序设计考试大纲
全国计算机等级考试二级Python语言程序设计考试大纲(2018年版) 基本要求 掌握Python语言的基本语法规则. 掌握不少于2个基本的Python标准库. 掌握不少于2个Python第三方库,掌 ...
- Python语言程序设计之二--用turtle库画围棋棋盘和正、余弦函数图形
这篇笔记依然是在做<Python语言程序设计>第5章循环的习题.其中有两类问题需要记录下来. 第一是如何画围棋棋盘.围棋棋盘共有19纵19横.其中,位于(0,0)的星位叫天元,其余8个星位 ...
- Python语言程序设计之一--for循环中累加变量是否要清零
最近学到了Pyhton中循环这一章.之前也断断续续学过,但都只是到了函数这一章就停下来了,写过的代码虽然保存了下来,但是当时的思路和总结都没有记录下来,很可惜.这次我开通了博客,就是要把这些珍贵的学习 ...
- Python语言程序设计之三--列表List常见操作和错误总结
最近在学习列表,在这里卡住了很久,主要是课后习题太多,而且难度也不小.像我看的这本<Python语言程序设计>--梁勇著,列表和多维列表两章课后习题就有93道之多.我的天!但是题目出的非常 ...
- Python语言程序设计(1)--实例1和基本知识点
记录慕课大学课程<Python语言程序设计>的学习历程. 实例1:温度转换 #温度转换TempStr = input("请输入带有符号的温度值:") #TempStr是 ...
- Python语言程序设计学习 之 了解Python
Python简介 Python是一种面向对象的解释型计算机程序设计语言,由荷兰人Guido van Rossum于1989年发明,第一个公开发行版发行于1991年. Python是纯粹的自由软件,源代 ...
- 【学习笔记】PYTHON语言程序设计(北理工 嵩天)
1 Python基本语法元素 1.1 程序设计基本方法 计算机发展历史上最重要的预测法则 摩尔定律:单位面积集成电路上可容纳晶体管数量约2年翻倍 cpu/gpu.内存.硬盘.电子产品价格等都遵 ...
- Python语言程序设计(3)--实例2-python蟒蛇绘制-turtle库
1. 2. 3.了解turtle库 Turtle,也叫海龟渲染器,使用Turtle库画图也叫海龟作图.Turtle库是Python语言中一个很流行的绘制图像的函数库.海龟渲染器,和各种三维软件都有着良 ...
- 全国计算机等级考试二级教程2019年版——Python语言程序设计参考答案
第二章 Python语言基本语法元素 一.选择题C B B C A D B A D B二.编程题1.获得用户输入的一个整数N,计算并输出N的32次方.在这里插入图片描述2.获得用户输入的一段文字,将这 ...
随机推荐
- swift 修改 Navigationbar Tabbar 字体颜色背景等属性
1.navigationBar的设置 let navColor = UIColor(red: 41/255, green: 160/255, blue: 230/255, alpha: 1) func ...
- MyBatisCodeHelper-Pro插件相关
参考 https://zhile.io/2019/04/23/mybatis-code-helper-pro-crack.html
- 推荐Pi(π)币,相当于比特币手机挖矿版
我为什么推荐这个? 说实话,之所以发出来还是因为如果用我的邀请码注册,双方的挖矿速度都会增加些,我的邀请码:leneing,有问题可以咨询我. Pi币简介 1.在这里强烈推荐Pi币,相当于比特币手机挖 ...
- mac 上更改环境变量
第一次配置Mac的环境变量,到网上转了一圈才找到正确方法. 打开终端,新建.bash_profile文件在~/目录下(如果电脑里已经有了这个文件,跳过这一步) touch ~/.bash_profil ...
- Appium移动自动化测试-----(一)Appium介绍
1.特点 appium 是一个自动化测试开源工具,支持 iOS 平台和 Android 平台上的原生应用,web应用和混合应用. “移动原生应用”是指那些用iOS或者 Android SDK 写的应用 ...
- Google大数据三大论文
简介:https://blog.csdn.net/w1573007/article/details/52966742 论文中英文版下载http://pan.baidu.com/s/1slUy4sl ...
- 异常查错java.net.SocketException: Connection reset
用httpclient访问后台接口报错java.net.SocketException: Software caused connection abort: recv failed,百度了一圈都说是由 ...
- Ly与lyon的巅峰对决,描色法
http://paste.ubuntu.com/14124956/ #include <stdio.h> #include <stdlib.h> struct node { i ...
- 更改 MATLAB 默认工作路径
步骤: 1. 以管理员身份打开记事本,然后打开 MATLAB安装路径\MATLAB\R2010b\toolbox\local\matlabrc.m 文件,即打开安装路径下的 matlabrc.m 文件 ...
- QT 设置程序图标
1.应用窗口左上角的图标.状态栏上显示的图标用setWindowIcon()函数: 2.可执行程序的图标设置: (1).右键项目添加一个资源文件 (2).导入.ico文件图标