问题大致是这样的:我下载了一堆文件放在某个文件夹下,这堆文件的名字都具有这样的格式 [Python乱码哇哇乱码哇哇].Python…. ,于是想把中括号里面的那堆乱码替换掉。
要实现其他字符的替换只需稍稍修改pat这个pattern和sub这个函数就可以了。比如说,要把所有文件名中的字符串A替换成字符串B,那pat和sub就作这样的修改
pat=re.compile(r’A')
re.sub(pat,’B',i)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| #! /usr/bin/env python
'''
This script is used to substitute all the file name in a directory
'''
import shutil
import os
import re
dir=r"/home/yarkee/test/" #The target directory
if not os.path.isdir(dir):
print "Error: The directory doesn't exist."
exit()
files=os.listdir(dir)
pat=re.compile(r'\[Python.*\]')
for i in files:
newFile=re.sub(pat,'Python',i) # 'Python' substitute for pat
print newFile
shutil.move(dir+i,dir+newFile) #Same as the linux command mv |
之前介绍过qsort,但后来发现稍微有点不妥,终止条件设置成if not L: return L ,有点多余,实际上L长度为1时就可return了,所以改了改终止条件.然后写了下冒泡排序和归并排序,测试了下,运行结果应该没问题.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| def qsort(L):
if len(L)<=1: return L
return qsort([x for x in L[1:] if x<L[0]])+L[0:1]+qsort([x for x in L[1:] if x>=L[0]])
def bubblesort(L):
for i in xrange(0,len(L)):
for j in xrange(len(L)-1,i,-1):
if L[j]<L[j-1]:
L[j-1],L[j]=L[j],L[j-1]
return L
def mergesort(L):
if len(L)<=1: return L
left=mergesort(L[0:len(L)/2])
right=mergesort(L[len(L)/2:len(L)])
result=[]
while len(left)>0 or len(right)>0:
if len(right)<=0 or (len(left)>0 and left[0]<=right[0]):
result.append(left.pop(0))
else:
result.append(right.pop(0))
return result |
在ubuntu中,发生按键错误时会发出相当刺耳的错误提示音,这简直是噪音,”Beep, beep”。比如说,在shell中已经没有输入字符了,却还在按backspace退格键,就会叫叫叫。之前还只在按下<C+F1>切换到字符界面后,才会因为按键错误而发出提示音。在Gnome图形界面中安然无恙。今天在Ubuntu上配了下compiz,弄了点特效。问题就来了。在Gnome环境中,按键错误也会”Beep, beep”地响。这还得了,按错键可是经常的时呀。
谷歌了一下,解决方法大致是这样的,切换到root权限,然后编辑当前用户的bashrc文件。
vim ~/.bashrc
在.bashrc的末尾加上这两行
setterm -blength 0 (这个是数字0,不是字母o)
保存,注销后重新登陆即可。
今天在珠三角技术沙龙发起者赖总的博客上 http://blog.csdn.net/lanphaday/archive/2011/03/31/6291668.aspx 看到一道Python面试题,赖总直接强悍地用Pipe写了个示例。我完全不懂Pipe这个模块的用法,试着用传统的方法写了遍。通过这道题,我发现正则语句”\W”很霸气。
题目是这样的:
读取文件,统计文件中每个单词出现的次数,然后按照次数高低排序。
代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| #! /usr/bin/env python
import re
addr="/home/yarkee/test.txt"
f=open(addr,"rb")
p=re.compile("\W"); #\W equals to [^a-zA-Z0-9]
text=f.read()
wn=re.split(p,text) #a list contain all the words
wd={} #a dic to count the appearence times
for i in range(0,len(wn)):
if wn[i]!='':
wn[i]=wn[i].strip()
wn[i]=wn[i].lower()
if wn[i] in wd:
wd[wn[i]]+=1
else:
wd[wn[i]]=1
wl=[(k,v) for k,v in wd.items()]
print sorted(wl,key=lambda x:x[1],reverse=True) #sort desc by times |
近期评论