您的位置:首页 > 编程语言 > Python开发

so cute are you python 18

2013-11-18 21:31 344 查看
1.python 实现在一个文件中查找字符串:

code:

#!/bin/evn python
#coding:utf-8
#FileName:grep.py
#History: 18-11-2013
#Function:show the function of grep ,found lines by keywords.
import os
def cdcGrep(cdcpath,keyword):
filelist=os.listdir(cdcpath)
for cdc in filelist:
if ".txt" in cdc:
cdcfile=open(cdcpath+cdc)
for line in cdcfile.readlines():
if keyword in line:
print line

if __name__=='__main__':
cdcGrep('/home/swfu/work/python/o/','python')


结果:

$python grep.py
-f /var/www/drupal/includes/database/mysql None

-f /var/www/drupal/includes/database/mysql None

root directory:_ /var/www/drupal/includes/database/sqlite

-f /var/www/drupal/includes/database/sqlite None

-f /var/www/drupal/includes/database/sqlite None

-f /var/www/drupal/includes/database/sqlite None

-f /var/www/drupal/includes/database/sqlite None

-f /var/www/drupal/includes/database/sqlite None


2.实现字符串的编码方式匹配:

code:

#!/bin/evn python
#coding:utf-8
#FileName:chardet
#History:18-11-2013
#function:encoding set by oneself.
def _smartcode(stream):
tryuni = ("gbk","gb2312","bg18030","big5","shift_jis","iso2022_kr","iso2022_j p","ascii","utf-8")
try:
for type in tryuni:
try:
ustring=unicode("%s}"%type+stream,type)
except:
continue
except:
return u"Bad unicode encode!"


3.规范化输出文本:

code:

#!/bin/evn python
#coding:utf-8
#FileName:cdctools.py
#History: 18-11-2013
#Function:show the function of list the directory contents.
import os
from chardet  import  _smartcode
def formatCDC(root,dirs,files):
export ="\n root directory:_ "+root+" \n"
for d in dirs:
export+="-d %s %s \n "%(root,_smartcode(d))
for f in files:
export +="-f %s %s \n"%(root,_smartcode(f))
export+="="*70
return export
def cdWalker(path,filename):
export=""
for root,dirs,files in os.walk(path):
export+=formatCDC(root,dirs,files)
open(filename,'w').write(export)

if __name__=='__main__':
cdWalker("/var/www/","test.txt")


结果:

$python cdctools.py
root directory:_ /var/www/
-d /var/www/ None
-d /var/www/ None
-d /var/www/ None
======================================================================
root directory:_ /var/www/sql
-f /var/www/sql None
-f /var/www/sql None
======================================================================
root directory:_ /var/www/drupal
-d /var/www/drupal None
-d /var/www/drupal None
-d /var/www/drupal None
-d /var/www/drupal None
-d /var/www/drupal None
-d /var/www/drupal None
-d /var/www/drupal None
-f /var/www/drupal None
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: