初学者求助:使用python进行文本搜索
现在有一个文本,内容如下:
>>cat a.txt
a=1,befc
a=11,azxv
a=2,azvf
a=231,fffe
a=24,zefg
需求:
写一完整python程序对其字符串进行排序处理,排序结果如下:
a=1,befc
a=2,azvf
a=11,azxv
a=24,zefg
a=231,fffe
先自己顶一个^_^
这样就可以了
Python code:
import re
file_a = open('a.txt')
pattern = re.compile('a=(\d+),(\w+)')
dict_1 = {}
for line in file_a:
s = pattern.match(line).group(1)
dict_1[int(s)] = line
list_1 = dict_1.keys()
list_1.sort()
for i in list_1:
print dict_1[i]
def my_cmp(a, b ):
a_value = int(a.lstrip('a=').split(',')[0])
b_value = int(b.lstrip('a=').split(',')[0])
return cmp(a_value, b_value)
lines = [ l.strip() for l in open('t.txt') if l.strip() ]
for l in sorted(lines, cmp = my_cmp):
print l
大型文件可能会挂掉
大型文件
http://code.activestate.com/recipes/576755/
多谢各位大侠,按二楼、三楼的code已经验证okay,再请教下:
如果文本变成多段,每段通过/*CSDN*/分开,中间有空行。段的数量实际情况很多,并且每段数字前的索引相同,但不同段间的索引不同)
>>cat a.t
相关问答:
python和pyqt以及Eric4都已经配置好了,打开Eric4写个python程序比如简单的
print“hello,world”,怎么编译运行了,Start菜单的所有命令都出现和图中差不多的对话框,应当怎么运行了?
求大家指教
没有人用 ......
已知Python 中:
s = unicode("测试", "gb2312")
s = u'\u6d4b\u8bd5'
print s
测试
在Delphi里面如何将\u6d4b\u8bd5这样的还原成Gb2312的汉字呢?
找到个方法
......
大家好,我是一个新手,刚开始学python,但是刚开始的helloworld都没法打印,让我很无奈。
我的python安装路径为f:\python31。在path中也设置对了,在windows下运行是这样显示的,希望各位前辈指点一下。谢谢
Pyth ......
现在脚本语言的能力几乎为0,下学期准备补一下,初步圈定Lua、Python(唉,学C出身的,对效率有变态的追求,这俩算是脚本里比较快的)。
Lua的东西小,中文资料也非常全,先学吧;Python的官网现在已经没有墙 ......