1. 程式人生 > 其它 >python處理文字檔案內容專題 -

python處理文字檔案內容專題 -

1.讀取一個文字檔案之後得到裡面出現最多的關鍵字的程式碼如下:
from time import time
from operator import itemgetter
def test():
# 取 10 個,有需要可以修改, 及定義讀取的檔案 test.txt
iList = 10
strFileName = 'test.txt'

count = {}
for word in open(strFileName).read().split():
if count.has_key(word):
count[word] = count[word] + 1
else:
count[word] = 1
print sorted(count.iteritems( ), key=itemgetter(1), reverse=True)[0:iList]

2.簡單講一下python中的正則表示式處理問題
字串替換
1.替換所有匹配的子串

1#用newstring替換subject中所有與正則表示式regex匹配的子串
2result = re.sub(regex, newstring, subject)
2.替換所有匹配的子串(使用正則表示式物件)

1reobj = re.compile(regex)
2result = reobj.sub(newstring, subject)
現在來查一下如何找到我們所需要的正則表示式呢?依照什麼樣的格式進行匹配操作的。

3.有如下的一個文字檔案我只需要讀取出來aa=的值
aa=123123
bb=456456
cc=45654656
aa=sdfsdf
fr=54fg
aa=65765
程式碼如下 :
import re

fp = open('t1.txt', "r")

content = fp.read()
s = re.findall(r'^aa=(.*)', content, re.M)
print s

4.正則表示式中的相關特殊字元

正則表示式

就個人而言,主要用它來做一些複雜字串分析,提取想要的資訊
學習原則:夠用就行,需要的時候在深入

現總結如下:

正則表示式中特殊的符號:

“.” 表任意字元
“^ ” 表string起始
“$” 表string 結束
“*” “+” “?” 跟在字元後面表示,0個——多個, 1個——多個, 0個或者1個
*?, +?, ?? 符合條件的情況下,匹配的儘可能少//限制*,+,?匹配的貪婪性
{m} 匹配此前的字元,重複m次
{m,n} m到n次,m,n可以省略

舉個例子 ‘a.*b’ 表示a開始,b結束的任意字串
a{5} 匹配連續5個a

[] 表一系列字元 [abcd] 表a,b,c,d [^a] 表示非a
| A|B 表示A或者B , AB為任意的正則表示式 另外|是非貪婪的如果A匹配,則不找B
(…) 這個括號的作用要結合例項才能理解, 用於提取資訊

\d [0-9]
\D 非 \d
\s 表示空字元
\S 非空字元
\w [a-zA-Z0-9_]
\W 非 \w

一:re的幾個函式

1: compile(pattern, [flags])
根據正則表示式字串 pattern 和可選的flags 生成正則表示式 物件

生成正則表示式 物件(見二)

其中flags有下面的定義:
I 表示大小寫忽略
L 使一些特殊字符集,依賴於當前環境
M 多行模式 使 ^ $ 匹配除了string開始結束外,還匹配一行的開始和結束
S “.“ 匹配包括‘\n’在內的任意字元,否則 . 不包括‘\n’
U Make \w, \W, \b, \B, \d, \D, \s and \S dependent on the Unicode character properties database
X 這個主要是表示,為了寫正則表示式,更可毒,會忽略一些空格和#後面的註釋

其中S比較常用,
應用形式如下
import re
re.compile(……,re.S)

2: match(pattern,string,[,flags])
讓string匹配,pattern,後面分flag同compile的引數一樣
返回MatchObject 物件(見三)

3: split( pattern, string[, maxsplit = 0])
用pattern 把string 分開
>>> re.split(’\W+’, ‘Words, words, words.’)
['Words', 'words', 'words', '']
括號‘()’在pattern內有特殊作用,請查手冊

4:findall( pattern, string[, flags])
比較常用,
從string內查詢不重疊的符合pattern的表示式,然後返回list列表

5:sub( pattern, repl, string[, count])
repl可以時候字串,也可以式函式
當repl是字串的時候,
就是把string 內符合pattern的子串,用repl替換了

當repl是函式的時候,對每一個在string內的,不重疊的,匹配pattern
的子串,呼叫repl(substring),然後用返回值替換substring

>>> re.sub(r’def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):’,
… r’static PyObject*\npy_\1(void)\n{’,
… ‘def myfunc():’)
’static PyObject*\npy_myfunc(void)\n{’

>>> def dashrepl(matchobj):
… if matchobj.group(0) == ‘-’: return ‘ ‘
… else: return ‘-’
>>> re.sub(’-{1,2}’, dashrepl, ‘pro—-gram-files’)
‘pro–gram files’

二:正則表示式物件 (Regular Expression Objects )

產生方式:通過 re.compile(pattern,[flags])回

match( string[, pos[, endpos]]) ;返回string[pos,endpos]匹配
pattern的MatchObject(見三)

split( string[, maxsplit = 0])
findall( string[, pos[, endpos]])
sub( repl, string[, count = 0])
這幾個函式和re模組內的相同,只不過是呼叫形式有點差別

re.幾個函式和 正則表示式物件的幾個函式,功能相同,但同一程式如果
多次用的這些函式功能,正則表示式物件的幾個函式效率高些

三:matchobject

通過 re.match(……) 和 re.compile(……).match返回

該物件有如下方法和屬性:

方法:
group( [group1, ...])
groups( [default])
groupdict( [default])
start( [group])
end( [group])

說明這幾個函式的最好方法,就是舉個例子

matchObj = re.compile(r”(?P\d+)\.(\d*)”)
m = matchObj.match(’3.14sss’)
#m = re.match(r”(?P\d+)\.(\d*)”, ‘3.14sss’)

print m.group()
print m.group(0)
print m.group(1)
print m.group(2)
print m.group(1,2)

print m.group(0,1,2)
print m.groups()
print m.groupdict()

print m.start(2)
print m.string

輸出如下:
3.14
3.14
3
14
(’3′, ‘14′)
(’3.14′, ‘3′, ‘14′)
(’3′, ‘14′)
{’int’: ‘3′}
2
3.14sss

所以group() 和group(0)返回,匹配的整個表示式的字串
另外group(i) 就是正則表示式中用第i個“()” 括起來的匹配內容
(’3.14′, ‘3′, ‘14′)最能說明問題了。

更進一步的學習,請看手冊

3.Python中刪除掉檔案

import os

刪除檔案:
os.remove()

刪除空目錄:
os.rmdir()

遞迴刪除空目錄:
os.removedirs()

遞迴刪除目錄和檔案(類似DOS命令DeleteTree):
方法1:自力更生,艱苦創業

# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))

方法2:前人栽樹,後人乘涼
import shutil
shutil.rmtree()

一行搞定 __import__('shutil').rmtree()

程式碼如下:

def rewriteFile(self,condition,newValue):
memoryFile = [] #get these file content
fp = open (self.path,'r+')
for line in fp.readlines():
if (re.search("^"+condition,line)):
strs = str(re.sub(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', newValue, line))
memoryFile.append(strs)
continue
memoryFile.append(line)
fp.close()
os.remove(self.path)
newfiles=open(self.path,'w')
for line in memoryFile:
newfiles.write(line)
newfiles.close()

可以將一個文字檔案中的內容提取出來然後搜尋出來想要替換掉的文字之後進行將相關的內容插入到文字檔案中去然後再覆蓋掉!