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的更多相关文章

  1. 【任务】Python语言程序设计.MOOC学习

    [博客导航] [Python导航] 任务 18年11月29日开始,通过9周时间跨度,投入约50小时时间,在19年1月25日之前,完成中国大学MOOC平台上的<Python语言程序设计>课程 ...

  2. 全国计算机等级考试二级Python语言程序设计考试大纲

    全国计算机等级考试二级Python语言程序设计考试大纲(2018年版) 基本要求 掌握Python语言的基本语法规则. 掌握不少于2个基本的Python标准库. 掌握不少于2个Python第三方库,掌 ...

  3. Python语言程序设计之二--用turtle库画围棋棋盘和正、余弦函数图形

    这篇笔记依然是在做<Python语言程序设计>第5章循环的习题.其中有两类问题需要记录下来. 第一是如何画围棋棋盘.围棋棋盘共有19纵19横.其中,位于(0,0)的星位叫天元,其余8个星位 ...

  4. Python语言程序设计之一--for循环中累加变量是否要清零

    最近学到了Pyhton中循环这一章.之前也断断续续学过,但都只是到了函数这一章就停下来了,写过的代码虽然保存了下来,但是当时的思路和总结都没有记录下来,很可惜.这次我开通了博客,就是要把这些珍贵的学习 ...

  5. Python语言程序设计之三--列表List常见操作和错误总结

    最近在学习列表,在这里卡住了很久,主要是课后习题太多,而且难度也不小.像我看的这本<Python语言程序设计>--梁勇著,列表和多维列表两章课后习题就有93道之多.我的天!但是题目出的非常 ...

  6. Python语言程序设计(1)--实例1和基本知识点

    记录慕课大学课程<Python语言程序设计>的学习历程. 实例1:温度转换 #温度转换TempStr = input("请输入带有符号的温度值:") #TempStr是 ...

  7. Python语言程序设计学习 之 了解Python

    Python简介 Python是一种面向对象的解释型计算机程序设计语言,由荷兰人Guido van Rossum于1989年发明,第一个公开发行版发行于1991年. Python是纯粹的自由软件,源代 ...

  8. 【学习笔记】PYTHON语言程序设计(北理工 嵩天)

    1 Python基本语法元素 1.1 程序设计基本方法 计算机发展历史上最重要的预测法则     摩尔定律:单位面积集成电路上可容纳晶体管数量约2年翻倍 cpu/gpu.内存.硬盘.电子产品价格等都遵 ...

  9. Python语言程序设计(3)--实例2-python蟒蛇绘制-turtle库

    1. 2. 3.了解turtle库 Turtle,也叫海龟渲染器,使用Turtle库画图也叫海龟作图.Turtle库是Python语言中一个很流行的绘制图像的函数库.海龟渲染器,和各种三维软件都有着良 ...

  10. 全国计算机等级考试二级教程2019年版——Python语言程序设计参考答案

    第二章 Python语言基本语法元素 一.选择题C B B C A D B A D B二.编程题1.获得用户输入的一个整数N,计算并输出N的32次方.在这里插入图片描述2.获得用户输入的一段文字,将这 ...

随机推荐

  1. 用easymock来mock数据

    昨天学习微信小程序了解了一个模拟数据的工具EasyMock,一早到公司就使用试试. 1.创建项目: 创建好如下所示: 2.创建接口: 点击右下角+号按钮即可. 操作栏依次是:预览,编辑,链接,更多操作 ...

  2. 单机prometheus vs 集群kube-prometheus+prometheus-operator

    prometheus 组件: node-exporter:9100端口 https://segmentfault.com/a/1190000017959127

  3. 10点睛Spring4.1-Application Event

    10.1 Application Event Spring使用Application Event给bean之间的消息通讯提供了手段 应按照如下部分实现bean之间的消息通讯 继承Application ...

  4. SVN增加访问用户

    1.在Linux中进入SVN配置文件目录. 2.authz是设置权限的,只读还是可读可写,passwd是增加访问用户的. vim passwd; vim authz;

  5. [转帖]大数据hadoop与spark的区别

    大数据hadoop与spark的区别 https://www.cnblogs.com/adnb34g/p/9233906.html Posted on 2018-06-27 14:43 左手中倒影 阅 ...

  6. windows密码凭据

  7. 20191031:Python取反运算详解

    20191031:Python取反运算详解 取反运算:~3 == 4 1.对于数字 3 =======>转换为二进制表示为011 2.对011取反为100 3.为什么表示-4 a.计算机用补码表 ...

  8. go http简单的表单处理

    //表单处理 package main import (     "net/http"     "io"     "fmt"     &qu ...

  9. SOS dp

    设$ans=\sum\limits_{A \cap B=\varnothing} f(A)g(B) $ 直接暴力枚举子集是$O(3^n)$, 一个技巧是先预处理出$h(S)=\sum\limits_{ ...

  10. 安装Nginx报错“Cannot retrieve metalink for repository: epel. Please verify its path and try again”

    CentOS 6.5中通过yum安装nginx报错. 搜了一下,很多都是修改某个配置文件的.但是在StackOverFlow的某个问题下,有人回答说修改配置文件并不是一个好的方法,虽然我采用了这个人的 ...