python处理文本

来源:互联网 发布:access数据库实验心得 编辑:程序博客网 时间:2024/05/29 09:11

最近在进行一些实验,需要进行文本处理,提取文本中关键的字段数据,得到表格,进行分析。在此简要的进行记录。

一、需求是这样的:

得到的GPGPU-Sim运行的程序文本文档。那么我现在需要提取目标对应的键值。比如文本中有如下:
A1 = B1
A2 = B2
A3 = B3
.....
A5 = B5
我现在需要提取出A2和A5对应的键值B2以及B5,按照"B2 B5"这样的格式写入到文本中去。如何用Python代码来实现?
需要提取的字段为:
[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. 'gpu_sim_insn',  
  2. 'gpu_ipc',  
  3. 'L1I_total_cache_accesses',  
  4. 'L1D_total_cache_accesses',  
  5. 'gpgpu_n_tot_thrd_icount',  
  6. 'gpgpu_n_tot_w_icount',  
  7. 'gpgpu_n_mem_read_local',  
  8. 'gpgpu_n_mem_write_local',  
  9. 'gpgpu_n_mem_read_global',  
  10. 'gpgpu_n_mem_write_global',  
  11. 'gpgpu_n_mem_texture',  
  12. 'gpgpu_n_mem_const',  
  13. 'gpgpu_n_load_insn',  
  14. 'gpgpu_n_store_insn',  
  15. 'gpgpu_n_shmem_insn',  
  16. 'gpgpu_n_tex_insn',  
  17. 'gpgpu_n_const_mem_insn',  
  18. 'gpgpu_n_param_mem_insn'  

代码如下:
[python] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import re  
  2. import sys  
  3. import os,glob  
  4.   
  5. #定义目录:目录下有多个文件需要处理  
  6. path = 'D:\\GPUClusters\\Stargazer-master\\EXP_RESULT'  
  7. #定义输出文件  
  8. fout = open("res.txt",'w')  
  9.   
  10. x = [  
  11.      'gpu_sim_insn',  
  12.      'gpu_ipc',  
  13.      'L1I_total_cache_accesses',  
  14.      'L1D_total_cache_accesses',  
  15.      'gpgpu_n_tot_thrd_icount',  
  16.      'gpgpu_n_tot_w_icount',  
  17.      'gpgpu_n_mem_read_local',  
  18.      'gpgpu_n_mem_write_local',  
  19.      'gpgpu_n_mem_read_global',  
  20.      'gpgpu_n_mem_write_global',  
  21.      'gpgpu_n_mem_texture',  
  22.      'gpgpu_n_mem_const',  
  23.      'gpgpu_n_load_insn',  
  24.      'gpgpu_n_store_insn',  
  25.      'gpgpu_n_shmem_insn',  
  26.      'gpgpu_n_tex_insn',  
  27.      'gpgpu_n_const_mem_insn',  
  28.      'gpgpu_n_param_mem_insn'  
  29.      ]  
  30.   
  31. #改变路径  
  32. os.chdir(path)  
  33.   
  34. #遍历目录下的所有文件  
  35. for filename in os.listdir():  
  36.     fs = open(filename,'r+')  
  37.     #处理文件中的每一行数据  
  38.     for line in fs.readlines():  
  39.         a = line.split()  
  40.         if a != [] and a[0in x:  
  41.             fout.write(a[-1]+'\t')  
  42.             if a[0] == 'gpgpu_n_param_mem_insn':  
  43.                 fout.write('\n')  
  44.                 break  
  45.                   
  46. fout.write('\n')    
  47. fout.close()  

解释一下代码中的几个问题:
1.在一个目录下有多个文件,每个文件都要读取一次,并进行文本处理,如何实现?
[python] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #比如d:\work下面是你要读取的文件,代码可以这样写:  
  2. import os  
  3. path = 'd:\\work' #or path = r'd:\work'  
  4. os.chdir(path)  
  5. for filename in os.listdir():  
  6.     file = open(filename,'r')  
  7.     for eachline in file.readlines():  
  8.         #process eachline  

2.Python中.read(), .readline(), .readlines()区别?

Python 将文本文件的内容读入可以操作的字符串变量非常容易。文件对象提供了三个“读”方法: .read()、.readline() 和 .readlines()。每种方法可以接受一个变量以限制每次读取的数据量,但它们通常不使用变量。 .read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。然而 .read() 生成文件内容最直接的字符串表示,但对于连续的面向行的处理,它却是不必要的,并且如果文件大于可用内存,则不可能实现这种处理。

.readline() 和 .readlines() 非常相似。它们都在类似于以下的结构中使用:

Python .readlines() 示例
[python] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. fh = open('c:\\autoexec.bat')  
  2. for line in fh.readlines():  
  3.     print line  

.readline() 和 .readlines() 之间的差异是后者一次读取整个文件,象 .read() 一样。.readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for ... in ... 结构进行处理。另一方面,.readline() 每次只读取一行,通常比 .readlines() 慢得多。仅当没有足够内存可以一次读取整个文件时,才应该使用 .readline()。

3.split方法:http://www.w3cschool.cc/python/att-string-split.html


二、再举一个简单的例子:
有如下文本"record.txt":
[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. boy:what's your name?  
  2. girl:my name is lebaishi,what about you?  
  3. boy:my name is wahaha.  
  4. girl:i like your name.  
  5. ==============================================  
  6. girl:how old are you?  
  7. boy:I'm 16 years old,and you?  
  8. girl:I'm 14.what is your favorite color?  
  9. boy:My favorite is orange.  
  10. girl:I like orange too!  
  11. ==============================================  
  12. boy:where do you come from?  
  13. girl:I come from SH.  
  14. boy:My home is not far from you,I live in Jiangsu province.  
  15. girl:Let's be good friends.  
  16. boy:OK!  
需求:将文件(record.txt)中的数据进行分割并按照以下规律保存起来:
--boy的对话单独保存为boy_*.txt的文件(去掉"boy:")
--girl的对话单独保存为girl_*.txt的文件(去掉"girl:")
--文件中总共有三段对话,分别保存为boy_1.txt,girl_1.txt,boy_2.txt,girl_2.txt,boy_3.txt,girl_3.txt共六个文件(文件中的不同的对话已经用"======="分割)。

代码:
[python] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. boy_log = []  
  2. girl_log = []  
  3. version = 1  
  4.   
  5. def save_to_file(boy_log,girl_log,version):  
  6.     filename_boy = 'boy_' + str(version) + ".txt"  
  7.     filename_girl = 'girl_' + str(version)  + ".txt"  
  8.     fb = open(filename_boy,"w")  
  9.     fg = open(filename_girl,"w")  
  10.     fb.writelines(boy_log)  
  11.     fg.writelines(girl_log)  
  12.               
  13.     fb.close()  
  14.     fg.close()  
  15.   
  16. def process(filename):  
  17.     file = open(filename,"r")  
  18.     for eachline in file.readlines():  
  19.         if eachline[:6] != "======":  
  20.             mylist = eachline.split(":")  
  21.             if mylist[0] == "boy":  
  22.                 global boy_log  
  23.                 boy_log.append(mylist[-1])  
  24.             else:  
  25.                 global girl_log  
  26.                 girl_log.append(mylist[-1])  
  27.         else:  
  28.             global version  
  29.             save_to_file(boy_log,girl_log,version)  
  30.             version += 1  
  31.             boy_log = []  
  32.             girl_log = []  
  33.               
  34.     save_to_file(boy_log,girl_log,version)  
  35.   
  36. if __name__ == "__main__":  
  37.     fn = "record.txt"  
  38.     process(fn)  


两个例子都是非常基础也很使用的,记录下来以便以后查阅。

再来一个简单的需求,我需要获取Linux上的ipv4的eth0地址,代码如下:
[python] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #/usr/bin/python  
  2.   
  3. import sys  
  4. import os  
  5.   
  6. os.system("ifconfig > ip.info")  
  7.   
  8. fs = open("ip.info",'r+')  
  9.   
  10. flag = 0  
  11.   
  12. def get_ip():  
  13.     for line in fs.readlines():  
  14.         a = line.split()  
  15.         if a != [] and a[0] == "eth0":  
  16.             flag = 1  
  17.         if a != [] and a[0] == "lo":  
  18.             flag = 0  
  19.   
  20.         if flag == 0:  
  21.             continue  
  22.         else:  
  23.             for item in a:  
  24.                 if a[0] == "inet" and item[0:5] == "addr:":  
  25.                     return item[5:]  
  26.   
  27. ip = get_ip()  
  28. print ip  

注明出处:http://blog.csdn.net/lavorange/article/details/41647091
0 0
原创粉丝点击