博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python初学者(续1)
阅读量:4030 次
发布时间:2019-05-24

本文共 5865 字,大约阅读时间需要 19 分钟。

转自:https://piao.blog.ustc.edu.cn/?p=151

摘自:《
Python编程实践
8、文件处理(
输入(读取),输出(写入,追加),处理)
  • 例如:
    • input=open(“D:\\test.txt”,”r”)
    • for line in input:
      • line=line.strip()  #去掉首尾空格
      • print(line)
    • input.close()
  • 互联网上的文件:urlopen(import urllib
    • 例如:
      • import urllib
      • url=””
      • web_page=urllib.urlopen(url)
      • for line in web_page
        • line=line.strip()
        • print(line)
      • web_page.close()
  • 将文件名作为参数传入
    • import sys
    • def process_file(filename):
      • ”’Open, read, and print a file.”’
      • input=open(filename,”r”)
      • for line in imput:
        • line=line.strip()
        • print(line)
      • input.close()
    • if __name__==”__main__”:
      • process_file(sys.argv[1])
  • 跳过文件头(#开头)(读文件只能前进,不能后退)
    • def skip_header(r):
      • ”’skip the header in readr r, return the first real piece of data”’
      • line=r.readline()
      • while line.startswith(‘#’):
        • line=r.readline()
      • #now line contains the first real piece of data
      • return line
    • def process_file(filename):
              ”’Open, read, and print a file.”’
              inputfile=
      open(filename,”r”)
              line=skip_header(inputfile).strip()
              print(line)
              for line in inputfile:
                      line=line.
      strip()
                      
      print(line)
              inputfile.
      close()
  • 含有多个字段的记录,空白符分隔
    • test.txt里面有数据格式如下:
      • 91.3    11.236
      • 56.2     12.364
      • 1234    235.5
      • ……
      • starts=[]
      • contracts=[]
      • input=open(“test.txt”,”r”)
      • for line in r:
        • start,contract=line.split()
        • starts.append(float(start))
        • contracts.append(float(contract))
      • input.close()
  • 定位数据(有些文件格式不用分隔符隔开各个字段,行内的各个字段都位于某个固定的位置上,例如第1至第8个字符用于存储日志等)
    • def read_weather_data(r):
      • ”’Read the weather data from reader r in fixed-width format
      • The fields are:
        • 1~8      YYYYMMDD(date)
        • 9~14    DDMMSS(latitude)
        • 15~20  DDMMSS(longitude)
        • 21~26   FF.FFF(temp,deg,C)
        • 27~32   FF.FFF(humidity,%)
        • 33~38   FF.FFF(pressure,kPa)
      • The result is a list of tumples:
        • ((Yr,Mo,Day),(Deg,Min,Sec),(Deg,Min,Sec),(Temp,Hum,Press),)”’
      • result=[]
      • for line in r:
        • year=int(line[0:4])
        • month=int(line[4:6])
        • day=int(line[6:8])
        • lat_deg=int(line[8:10])
        • lat_min=int(line[10:12])
        • lat_sec=int(line[12:14])
        • long_deg=int(line[14:16])
        • long_min=int(line[16:18])
        • long_sec=int(line[18:20])
        • temp=float(line[20:26])
        • hum=float(line[26:32])
        • press=float(line[32:38])
        • result.append((year,month,day),(lat_deg,lat_min,lat_sec),(long_deg,long_min,long_sec),(temp,hum,press))
      • return result
    • 改进 
      • def read_weather_data(r):
        • ”’Read the weather data from reader r in fixed-width format
        • The fields are:
          • 1~8      YYYYMMDD(date)
          • 9~14    DDMMSS(latitude)
          • 15~20  DDMMSS(longitude)
          • 21~26   FF.FFF(temp,deg,C)
          • 27~32   FF.FFF(humidity,%)
          • 33~38   FF.FFF(pressure,kPa)
        • The result is a list of values(not tumples):
          • (YY,MM,DD,DD,MM,SS,DD,MM,SS,Temp,Hum,Press)”’
        • fields=((4,int),(2,int),(2,int),         #date
          • (2,int),(2,int),(2,int),            #latitude
          • (2,int),(2,int),(2,int),            #longitude
          • (6,float),(6,float),(6,float))  #data
        • #for each record
        • for line in r:
          • start=0
          • record=[]
          • for (width,target_type) in fields:
            • text=line[start,start+width]
            • field=target_type(text)
            • record.append(field)
            • start+=width
          • result.append(record)
        • return result
  • 多行记录
    • 文件如下:(蛋白质数据库格式)
      • COMPND   AMMONIA
      • ATOM    1  N  0.257  -0.363  0.000
      • ATOM    3  H  0.257  0.727   0.000
      • END
      • COMPND   AMMONIA
        ATOM    1  N  0.257  -0.363  0.852
        ATOM    3  H  0.257  0.727   -0.901
        END
      • ……
    • def read_all_molecules(r):#读取所有分子函数
      • ”’Read zero or more molecules from reader r”’
      • result=[]
      • reading=True
      • while reading:
        • molecule=read_molecule(r)    if molecule:
          • result.append(molecule)
        • else:
          • reading=False
      • return result
    • def read_molecule(r):#读取单个分子函数
      • line=r.readline()
      • if not line:
        • return None
      • key,name=line.split()
      • molecule=[name]
      • reading=True
      • while reading:
        • line=r.readline()
        • if line.startswith(‘END’):
          • reading=False
        • else:
          • key,num,type,x,y,z=line.split()
          • molecule.append((type,x,y,z))
      • return molecule
  • 写入文件
    • 例如:输入文件的格式为:每行两个数字,各数字之间以空格分隔;输出文件的格式为每一行三个数据(前两个来自输入文件,后一个是前两个之和),数字之间以一个空格分隔,
    • def sum(inputfile,outputfile):
      • outputfile=open(outputfile,”w”)
      • for line in inputfile:
        • operands=line.split()
        • print(‘operands’,operands)
        • sum=float(operands[0]+operands[1])
        • new_line=line.strip()+’ ‘+str(sum)+’\n’
        • outputfile.write(new_line)
      • outputfile.close()
9、集合和字典
  • 集合set():一个由唯一元素组成的非排序集合体(collection);使用set()可创建出一个新的空集合;如果要创建出带值的集合,则初始值必须是列表或者元组;例如set((2,3,5)) 或者 set(([2,3,5]))
    • 集合运算:并(union——|)、交(intersection ——&)、添加(add)、移除(removeclear)、difference(差集——set1-set2)、issubset(是子集?set1<=set2)、issuperset(是超集?set1>=set2)、symmetric_difference(异或 ∧)
    • 集合的存储:散列表(hash table)——当有元素加入到集合中时,就会计算该元素的散列码(hash code),散列码是一个整数,拥有相等值的元素的散列码肯定是相同的;只允许集合含有不可变(immutable)值(布尔值、数字、字符串等);
    • 集合本身是可变的,所以不能再集合中存放另一个集合;为了解决这个问题,Python提供了一个冻结集合(frozen set)的数据类型,frozenset()可创建出空的冻结集合;frozenset(values)可创建出带有值的冻结集合,values可以是列表、元组、集合或者别的集合体
  • 字典(Dictionary):是由一个键/值对组成的非排序可变集合体。将键/值对放到一对花括号中即可创建出字典,为了获取指定键所关联的值,将键放到一对方括号中即可。{}——空字典
    • 例如:birds={‘canada goose':3,’northern fulmar':1};
    • 例如:birds[‘canada goose’]=33
    • 循环:for x in birds:
        • print(x,birds[x])
      • 分配给循环变量的是键
    • 方法:
      • clear——清空字典内容;
      • get——返回指定键所关联的值;如果指定键不存在,则返回默认值
      • keys——以列表的形式返回字典的所有键
      • items——返回(key,item)列表
      • values——以列表的形式返回字典的所有值,
      • update——用另一个字典的内容对当期字典进行更新;例如scientists.update(temp)
      • iteritems——根据实际情况一个一个地返回键值对:例如for (key,value) in dictionary.iteritems():——python 3以后没有了
10、算法
  • 搜索:
    • min——最小值
    • index——获取索引;例如:low=min(counts)
      • min_index=counts.index(low)
    • sort——排序(升序)
  • 计时——运行时间、占用内存
11、搜索和排序
  • 搜索
    • 线性搜索:
      • index()——从列表最前面开始,诸葛检查所有的元素
      • 基本线性搜索:
        • def linear_search(v,L):
          • i=0
          • while i!=len(L) and L[i]!=v:
            • i=i+1
          • return i
      • for循环型线性搜索:
        • def linear_search(v,L):
          • i=0
          • for value in L:
            • if value==v:
              • return i
            • i+=1
          • return i
      • 哨兵搜索:
        • def linear_search(v,L):
          • L.append(v)  #增加一个哨兵,这样就可以确保能够找到v
          • i=0
          • while L[i]!=v:
            • i=i+1
          • L.pop(v)
          • return i
      • 测定搜索的时间
        • import time
        • import linear_search_1
        • def time_it(search,v,L):
          • t1=time.time()  #ms
          • search(v,L)
          • t2=time.time()
          • return (t2-t1)   #
    • 二分搜索
      • def binary_search(v,L):
        • i=0
        • j=len(L)-1
        • while i!=j+1:
          • m=(i+j)/2
          • if L[m]<v:
            • i=m+1
          • else:
            • j=m-1
        • if 0<=i<len(L) and L[i]==v:
          • return i
        • else:
          • return -1
  • 排序
    • sort()
    • 选择排序:不断地从未排序区域中找出下一个最小值,并将其放倒已排序区域的末尾
      • def selection_sort(L):
        • i=0
        • while i!=len(L):
          • smallest=find_min(L,i)
          • L[i],L[smallest]=L[smallest],L[i]
          • i=i+1
      • def find_min(L,b):
        • smallest=b
        • i=b+1
        • while i!=len(L):
          • if L[i]<L[smallest]:
            • smallest=i
          • i=i+1
        • return smallest
    • 插入排序——直接从未排序区域拿出一个值,并将其插入到已排序区域中适当的位置
    • 冒泡排序
    • 合并排序(时间Nlog2(N))
    • 快速排序
    • 堆排序

转载地址:http://wgmbi.baihongyu.com/

你可能感兴趣的文章
eclipse 导入先前存在的项目
查看>>
GNU hello代码分析
查看>>
Qt继电器控制板代码
查看>>
busybox passwd修改密码
查看>>
wpa_supplicant控制脚本
查看>>
rfkill: WLAN hard blocked
查看>>
gstreamer相关工具集合
查看>>
arm 自动升级脚本
查看>>
RS232 四入四出模块控制代码
查看>>
gstreamer插件之 videotestsrc
查看>>
autoupdate script
查看>>
linux 驱动开发 头文件
查看>>
/etc/resolv.conf
查看>>
container_of()传入结构体中的成员,返回该结构体的首地址
查看>>
linux sfdisk partition
查看>>
ipconfig,ifconfig,iwconfig
查看>>
opensuse12.2 PL2303 minicom
查看>>
电平触发方式和边沿触发的区别
查看>>
网络视频服务器移植
查看>>
Encoding Schemes
查看>>