问题大致是这样的:我下载了一堆文件放在某个文件夹下,这堆文件的名字都具有这样的格式 [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 |
今天在珠三角技术沙龙发起者赖总的博客上 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 |
Python语言,辗转相除法求多个数的最大公约数,可以是2个,3个,……XX个数的公约数,这些数全部扔到T这个元组里面就行了。
这个例子,求256,4096,8192的最大公约数,结果当然是256了。
Python也太简洁了吧……
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| #! /usr/bin/env python
def gcd(argv):
L=list(argv)
while len(L)>1:
a=L[len(L)-2]
b=L[len(L)-1]
L=L[:len(L)-2]
while b:
a,b=b,a%b
L.append(a)
return a
T=(256,4096,8192)
print gcd(T) |
近期评论