常用的Python代码段
过滤列表
1 #filter out empty strings in a sting list 2 list = [x for x in list if x.strip()!='']
一行一行地读文件
1 with open("/path/to/file") as f: 2 for line in f: 3 print line
逐行写文件
1 f = open("/path/tofile", 'w') 2 for e in aList: 3 f.write(e + "\n")f.close()
正则匹配查找
1 sentence = "this is a test, not testing." 2 it = re.finditer('\\btest\\b', sentence) 3 for match in it: 4 print "match position: " + str(match.start()) +"-"+ str(match.end())
正则匹配搜索
1 m = re.search('\d+-\d+', line) #search 123-123 like strings 2 if m: 3 current = m.group(0)
查询数据库
1 db = MySQLdb.connect("localhost","username","password","dbname") 2 cursor = db.cursor() 3 sql = "select Column1,Column2 from Table1" 4 cursor.execute(sql) 5 results = cursor.fetchall() 6 for row in results: 7 print row[0]+row[1] db.close()
用指定字符连接列表
1 theList = ["a","b","c"] 2 joinedString = ",".join(theList)
去除重复元素
1 targetList = list(set(targetList))
在一列字符串中去除空字符串
1 targetList = [v for v in targetList if not v.strip()==''] 2 # or 3 targetList = filter(lambda x: len(x)>0, targetList)
将一个列表连接到另一个列表后面
1 anotherList.extend(aList)
遍历一个字典
1 for k,v in aDict.iteritems(): 2 print k+v
检查一列字符串中是否有任何一个出现在指定字符串里
1 if any(x in targetString for x in aList): 2 print "true"