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. 分类:logistic回归

    import numpy as np import matplotlib.pyplot as plt x=np.linspace(-1,1,200) y=1/(1+np.exp(10*x-1)) pl ...

  2. Swift4.0复习访问控制与作用域

    1.访问等级: open: 可以继承,可以重写. public: “public 访问等级能用于修饰所有文件作用域的函数.对象.协议.枚举.结构体.类以及各种类型中的属性与方法.用 public 所修 ...

  3. k8s中正确删除一个pod

    1.先删除pod 2.再删除对应的deployment 否则只是删除pod是不管用的,还会看到pod,因为deployment.yaml文件中定义了副本数量 实例如下: 删除pod [root@tes ...

  4. @PathVariable设置为空的问题(required=false)

    参考了:http://www.imooc.com/qadetail/268268 最近学习springMVC的时候,学到@PathVariable后,发现@PathVariable有个required ...

  5. Linux脚本检测当前用户是否为root用户

    #/bin/bash if [ $UID -ne 0 ]; then echo Non root user. Please run as root. else echo Root user fi

  6. 【嵌入式硬件Esp32】ESP32使用visual studio cod界面

     如何下载安装IDE Visual Studio Code大家可以在微软的官网上根据自身的开发平台下载,至于安装方法就是无脑式地按Next就好了,下载地址如下所示: Visual Studio Cod ...

  7. 强制卸载 Visual studio 2017

    微软挖的坑,很是烦人.还好老外这篇文章亲测可行.懒得翻译了,权做笔记吧. 网址是:https://jessehouwing.net/visual-studio-2017-force-uninstall ...

  8. 使用 LVS 实现负载均衡原理及安装配置详解(课堂随笔)

    一.负载均衡LVS基本介绍 LB集群的架构和原理很简单,就是当用户的请求过来时,会直接分发到Director Server上,然后它把用户的请求根据设置好的调度算法,智能均衡地分发到后端真正服务器(r ...

  9. iOS-Xib获取view尺寸的问题

    用xib创建的视图,我们一般要在控制器中获取对应的view尺寸,但经常我们没法获取到,或者获取的不准 如果通过xib加载出来的view尺寸是不正确的, 在xib中这个view不管你怎么设置都是治标不治 ...

  10. vue-cli3 + ts 定义全局方法

    一.定义全局方法不生效  虽然在main.ts当中定义了全局方法,但是在使用的时候根本找不到,也是无语了. 二.解决方法 我在网上找了很多方法,其中很多大神都是这样做的:  但是,我这样写了还是不生效 ...