Programming
1.Analysing a Text File
Look at the file xian_info.txt which is like this:
Xi'an
China8705600Northwest Chang'an Shaanxi_Normal Xidian
34 16 N 108 54E3 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'''
#读文件
defread_file_line(filename):
f=open(filename,encoding='utf-8')
lines=[]#lines=f.readlines()
for line inf.readlines():
line=line.strip('\n')
lines.append(line)#print(lines)
returnlines#获取大学
defget_universies(info):return info.split(' ')#获取地址
defget_location(location):return location.split(' ')#获取温度
defget_temperature(temperature):return temperature.split(' ')#此方法是总方法,调用上述四个函数,用于处理文本
defprocess_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 inrange(0,len(data)):if int(data[i])<200:
f.write( ( data[i]+40 ).to_bytes( 1, byteorder='big' ) )