日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 代码转程序_精悍的Python代码段-转

發布時間:2023/12/10 python 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 代码转程序_精悍的Python代码段-转 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1 文件處理

readlines() 和 writelines()方法可以講列表元素依次寫到文件中;

file類本身沒有提供復制方法,可以使用read()和write()方法模擬實現文件的拷貝,也可以使用shutil模塊:

shutil.copyfile('hello.txt','hello2.txt')

shutil.move('hello.txt','../')

shutil.copyfile('hello2.txt','hello3.txt')

批量改變當前目錄中文件的名字:

方式一:

files = os.listdir(".")

for filename in files:

pos = filename.find(".");

if filename[pos+1:] == 'html':

newname = filename[:pos+1] + 'htm'

os.rename(filename,newname)

方式二:

files = os.listdir(".")

for filename in files:

li = os.path.splitext(filename)

if li[1] == 'html':

newname = li[0] + '.htm'

os.rename(filename,newname)

方式三:

可以使用glob模塊中的glob方法獲取指定條件的文件列表:

例如使用l = glob.glob('*.html')獲取html為后綴的文件

l = glob.glob('c:\\w*\\*.txt')獲取C盤中w開頭目錄中所有的文本文件。

統計文件中指定字符串的數量(是統計字符串而不是單詞,字符串可以不是整個單詞):

import re

def str_count(filename,s):

count = 0

f = file(filename,'r+')

for line in f.readlines():

li = re.findall(s,line);

if li.count(s) > 0:

count += li.count(s);

f.close()

return count

統計文件中指定單詞的數量:

def word_count(filename,word):

count = 0

f = file(filename,'r+')

for line in f.readlines():

p = r'\b'+word+r'\b'

print p

li = re.findall(p,line);

print li

if li.count(word) > 0:

count += li.count(word);

f.close()

return count

修改文件中指定字符串的代碼,這里面有兩種修改方式,即是否進行全詞匹配:

#f1源文件,f2修改后文件,s待修改的字符串,_s為改后字符串,whole是否全詞匹配,默認值0代表全詞匹配

def replace_str (file1,file2,s,_s,whole = 0):

f1 = file(file1,'r+')

f2 = file(file2,'w+')

p = r'\b' + s + r'\b'

if whole == 1:

p = s

for line in f1.readlines():

t = re.sub(p,_s,line)

f2.write(t)

f1.close()

f2.close()

difflib是python提供的比較序列(string list)差異的模塊。實現了三個類:

1>SequenceMatcher 任意類型序列的比較 (可以比較字符串)

2>Differ 對字符串進行比較

3>HtmlDiff 將比較結果輸出為html格式.

使用difflib進行序列的比較與結果輸出:

import difflib

from pprint import pprint

a = 'pythonclub.org is wonderful'

b = 'Pythonclub.org also wonderful'

s = difflib.SequenceMatcher(None, a, b)

print "s.get_matching_blocks():"

pprint(s.get_matching_blocks())

print

print "s.get_opcodes():"

for tag, i1, i2, j1, j2 in s.get_opcodes():

print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %? (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))

來看另一個例子:

def reportSingleFile(srcfile, basefile, rpt):

src = file(srcfile).read().split(' ')

base = file(basefile).read().split(' ')

import difflib

s = difflib.SequenceMatcher( lambda x: len(x.strip()) == 0, # ignore blank lines

base, src)

lstres = []

for tag, i1, i2, j1, j2 in s.get_opcodes():

print (tag, i1, i2, j1, j2)

#print lstres

if tag == 'equal':

pass

elif? tag == 'delete' :

lstres.append('DELETE (line: %d)' % i1)

lstres += base[i1:i2]

lstres.append(' ')

elif tag == 'insert' :

lstres.append('INSERT (line: %d)' % j1)

lstres += src[j1:j2]

lstres.append(' ')

elif tag == 'replace' :

lstres.append('REPLACE:')

lstres.append('Before (line: %d) ' % i1)

lstres += base[i1:i2]

lstres.append('After (line: %d) ' % j1)

lstres += src[j1:j2]

lstres.append(' ')

else:

pass

print ' '.join(lstres)

使用Differ進行字符串比較

import difflib

diff = difflib.Differ().compare("start up","starT u4p")

print "\n".join(list(diff))

使用HtmlDiff進行統計:

from difflib import *

s = HtmlDiff.make_file(HtmlDiff(),"start up","storT up")

f=open(r"C:/dong/result.html","w")

f.write(s)

f.close()

越來越發現python非常適合做一些日常開發的工具。平時,我們經常用一些比較工具,比較目錄、比較兩個文本文件的變化。最近發現,python的標準庫里居然帶了這些功能的算法。自己處理一下,就可以寫出一個很實用的比較工具了。文件和目錄比較Module叫做filecmp。最酷的是他提供了一個叫dircmp的類,可以直接比較兩個目錄。

目錄遍歷的三種方式:

1 使用遞歸函數:

def visitDir (path):

li = os.listdir(path)

for p in li:

pathname = os.path.join(path,p)

if not os.path.isfile(pathname):

visitDir(pathname)

else:

print pathname

2 使用os.path.walk()

import os,os.path

def visitDir (arg,dirname,names):

for filepath in names:

print os.path.join(dirname,filepath)

path1 = 'C:\\dong'

os.path.walk(path1,visitDir,())

3 使用os.walk()

def visitDir (path):

for root,dirs,files in os.walk(path):

for filepath in files:

print os.path.join(root,filepath)

path1 = 'C:\\dong'

visitDir(path1)

自己制作的簡單日志記錄文件:

#coding=gbk

import sys,time

sys.stderr = open("record.log","a")

f = open(r"hello.txt",'r')

t = time.strftime("%Y-%m_%d%X",time.localtime())

context = f.read()

if context:? #不為空

sys.stderr.write(t + " " + context)

else:

raise Exception,t+"異常信息"

使用Python模擬Java中的輸入和輸出流:

#coding=gbk def FileInputStream (filename): ??? try: ??????? f = open(filename) ??????? for line in f: ??????????? for byte in line: ??????????????? yield byte ??? except StopIteration,e: ??????? f.close() ??????? return ??? def FileOutputStream (inputStream,filename): ??? try: ??????? f = open(filename,'w') ??????? while True: ??????????? byte = inputStream.next() ??????????? f.write(byte) ??? except StopIteration,e: ??????? f.close() ??????? return

總結

以上是生活随笔為你收集整理的python 代码转程序_精悍的Python代码段-转的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。