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. 比较两个数组的键名,并返回交集:array_intersect_key

    $a1=array("a"=>"red","b"=>"green","c"=>&q ...

  2. CompletableFuture Quasar 等并发编程

    CompletableFuture基本用法 https://www.cnblogs.com/cjsblog/p/9267163.html Quasar https://blog.csdn.net/ma ...

  3. HTML布局排版2 div的和图片平铺方便管理

    在HTML里,由于浏览器显示器等差异,浏览器的宽度也会有变化,为了适应不同的宽度,需要用到平铺.例如页面前面的固定的条等,如果是纯色,可以用背景色,如果不是纯色,是渐变等,可以用条状图平铺.常见的布局 ...

  4. 【python基础】使用import导入相对路径的源文件

    前言 在编写python代码的过程中,不同路径下的源码文件该如何引用,这是个问题,本文针对这个问题介绍解决方法. 源码目录结构: . ├── conf.py ├── main.py ├── mod/ ...

  5. selenium3+Python3+sublime text3自动化登录

    前言: 对于初学者来说,python自带的IDLE,精简又方便,不过一个好的编辑器能让python编码变得更方便,更加优美些. 不过呢,也可以自己去下载其他更好用的代码编辑器,在这推荐: PyChar ...

  6. Samba访问控制smb.conf

    访问控制 Samba的访问控制通过hosts allow(配置允许访问的客户端).hosts deny(配置拒绝访问的客户端)两个参数实现. 在Samba中使用hosts allow.hosts de ...

  7. 【剑指offer】面试题 52. 两个链表的第一个公共结点

    面试题 52. 两个链表的第一个公共结点 NowCoder 题目描述 输入两个链表,找出它们的第一个公共结点. Java 实现 ListNode Class class ListNode { int ...

  8. [.Net Core] - 使用 NLog 记录日志到 Sql Server

    1. 使用 Nuget 安装 NLog. 2. 在 Sql Server 中创建 NLog 数据表. CREATE TABLE [dbo].[NLogInfo]( ,) NOT NULL, [Date ...

  9. CF197A Plate Game

    题目描述 你有一个长方形的桌子,长度 a ,宽度 b ,以及无限多的半径 r的圆盘. 两位玩家玩以下游戏:他们轮流把圆盘放在桌子上,使得盘子之间不能互相重叠(但他们的边缘可以互相接触),任何盘子上的任 ...

  10. FZU2018级算法第三次作业 3.16 station

    题目大意: 给出1-n共n个数的入栈顺序,可以随时出栈,求出栈的最大字典序. 输入示例 输出示例 51 2 3 4 5 5 4 3 2 1 54 2 5 3 1 5 3 2 4 1 题目分析: 假设目 ...