Programming

1.Analysing a Text File

Look at the file xian_info.txt which is like this:

  1. Xi'an
  2. China
  3. 8705600
  4. Northwest Chang'an Shaanxi_Normal Xidian
  5. 34 16 N 108 54 E
  6. 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:

  1. lines = []
  2. country = ''
  3. population = 0
  4. universities = []
  5. location = ()
  6. temperature = []
  7. 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.

  1. '''process_text.py'''
  2.  
  3. #读文件
  4. def read_file_line(filename):
  5. f=open(filename,encoding='utf-8')
  6. lines=[]
  7. #lines=f.readlines()
  8. for line in f.readlines():
  9. line=line.strip('\n')
  10. lines.append(line)
  11. #print(lines)
  12. return lines
  13. #获取大学
  14. def get_universies(info):
  15. return info.split(' ')
  16. #获取地址
  17. def get_location(location):
  18. return location.split(' ')
  19. #获取温度
  20. def get_temperature(temperature):
  21. return temperature.split(' ')
  22.  
  23. #此方法是总方法,调用上述四个函数,用于处理文本
  24. def process_text(filename):
  25. lines = []
  26. country = ''
  27. population = 0
  28. universities = []
  29. location = ()
  30. temperature = []
  31. info = {}
  32.  
  33. lines=read_file_line(filename)
  34. #print(lines)
  35. country=lines[0]
  36. #print(country)
  37. population=int(lines[1])
  38. #print(population)
  39. universities=get_universies(lines[2])
  40. #print(universities)
  41. location=get_location(lines[3])
  42. #print(location)
  43. temperature=get_location(lines[4])
  44. #print(temperature)
  45.  
  46. info={'country':country,'population':population,'universities':universities,'location':location,'temperature':temperature}
  47. return info
  1. '''test.py'''
  2. from process_text import *
  3.  
  4. info=process_text('xian_info.txt')
  5. 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.

  1. """changeBinaryFile.py"""
  2. f=open('it_building.bmp',"rb+")
  3. data=bytearray(f.read())
  4.  
  5. print(data[:54])
  6. for i in range(0,len(data)):
  7. if int(data[i])<200:
  8. 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. 数据标记系列——图像分割 & Curve-GCN

    在之前的文章中(参考:),我们提到了Polygon-RNN++在数据标注中的应用.今天不得不提到多伦多大学与英伟达联合公布的一项最新研究:Curve-GCN的应用结果显示图像标注速度提升10倍. Cu ...

  2. 关于Js异常

    一.Javascript的异常处理机制 当javascript代码中出现错误的时候,js引擎就会根据js的调用栈逐级寻找对应的catch,如果没有找到相应的catch handler或catch ha ...

  3. Python3 IO编程之StringIO和BytesIO

    StringIO 很多时候,数据读写不一定是文件,也可以在内存中读写. 要把str写入StringIO,我们需要先创建一个StringIO,然后像文件一样写入即可 >>> from ...

  4. iOS底层框架浅析

    1.简介 IOS是由苹果公司为iPhone.iPod touch和iPad等设备开发的操作系统. 2.知识点 iPhone OS(现在叫iOS)是iPhone, iPod touch 和 iPad 设 ...

  5. 安卓app和苹果app共用一个二维码

    应项目要求,现在安卓app和苹果app共用一个二维码,对外提供下载: <html> <head> <meta http-equiv="Content-Type& ...

  6. windows下大数据开发环境搭建(4)——Spark环境搭建

    一.所需环境 · Java 8 · Python 2.6+ · Scala · Hadoop 2.7+ 二.Spark下载与解压 http://spark.apache.org/downloads.h ...

  7. Ordered Neurons: Integrating Tree Structures Into Recurrent Neural Networks

    这是一篇发表在ICLR2019上的论文,并且还是ICLR2019的Best paper之一.该论文提出了能够学习树结构信息的ON-LSTM模型,这篇论文的开源代码可以在GitHub找到. 自然语言都是 ...

  8. xorm表结构操作实例

    获取数据库信息 package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "git ...

  9. jwt单点登入

    主要有以下三步:   项目一开始我先封装了一个JWTHelper工具包(GitHub下载),主要提供了生成JWT.解析JWT以及校验JWT的方法,其他还有一些加密相关操作.工具包写好后我将打包上传到私 ...

  10. ActiveMQ处理Message(String -javabean)

    一.ActiveMq想要实现必备的六要素(基于jms) //链接工厂.用于创建链接 private ConnectionFactory factory; //用于访问Mq的链接,由链接工厂创建 pri ...