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. 【Leetcode_easy】953. Verifying an Alien Dictionary

    problem 953. Verifying an Alien Dictionary solution: class Solution { public: bool isAlienSorted(vec ...

  2. ROW_NUMBER()函数使用详解

    原文地址:https://blog.csdn.net/qq_30908543/article/details/74108348 注:mysql貌似不适用,本人测试未成功,mysql实现方式可参考:ht ...

  3. element组件 MessageBox不能显示确认和取消按钮,记录正确使用方法!

    这里是局部引入 调用方式:

  4. 如何在Java中编写一个线程安全的方法?

    线程安全总是与多线程有关的,即一个线程访问或维护数据时遭到了其它线程的“破坏”,为了不被破坏,就要保持所维护变量的原子性: 1 局部变量总是线程安全的,因为每个线程都有自己的栈,而在方法中声明的变量都 ...

  5. mac 上更改环境变量

    第一次配置Mac的环境变量,到网上转了一圈才找到正确方法. 打开终端,新建.bash_profile文件在~/目录下(如果电脑里已经有了这个文件,跳过这一步) touch ~/.bash_profil ...

  6. [转帖]Java 2019 生态圈使用报告,这结果你赞同吗?

    Java 2019 生态圈使用报告,这结果你赞同吗? http://www.51testing.com/html/94/n-4462794.html 发表于:2019-10-15 17:10  作者: ...

  7. java生成验证码结合springMVC

    在用户登录的时候,为了防止机器人攻击都会设置输入验证码,本篇文章就是介绍java如何生成验证码并使用在springMVC项目中的. 第一步:引入生成图片验证码的工具类 import java.awt. ...

  8. 多线程(10) — Future模式

    Future模式是多线程开发中常用常见的一种设计模式,它的核心思想是异步调用.在调用一个函数方法时候,如果函数执行很慢,我们就要进行等待,但这时我们可能不着急要结果,因此我们可以让被调者立即返回,让它 ...

  9. win10安装Ubuntu,用Xshell连接

    一.安装Ubuntu 安装Ubuntu,安装过程就不详细说了,我是从微软商店下载的Ubuntu安装,没有用VMware,想用Xshell连接Ubuntu,中间一直出问题,现在解决,总结一下. 二.配置 ...

  10. 机器学习之主成分分析PCA原理笔记

    1.    相关背景 在许多领域的研究与应用中,通常需要对含有多个变量的数据进行观测,收集大量数据后进行分析寻找规律.多变量大数据集无疑会为研究和应用提供丰富的信息,但是也在一定程度上增加了数据采集的 ...