`
foreversunyao
  • 浏览: 204523 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

python处理文本文件内容专题

阅读更多

转载 http://blog.sina.com.cn/s/blog_5d236e060100enrm.html

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()

可以将一个文本文件中的内容提取出来然后搜索出来想要替换掉的文本之后进行将相关的内容插入到文本文件中去然后再覆盖掉!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics