转载 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()
可以将一个文本文件中的内容提取出来然后搜索出来想要替换掉的文本之后进行将相关的内容插入到文本文件中去然后再覆盖掉!
相关推荐
Python写的根据文本文件内容生成图片,需要安装PIL
【转】python 处理文本文件 2010-06-01 11:10:53" 分类: Python " 标签:python cookbook "字号 订阅 1.从文件读取文本或数据 一次将文件内容读入一个长字符串的最简便方法 如:all_the_text = open('thefile.txt')...
用Python实现的搜索本地文本文件内容的小程序。从而学习Python I/O方面的知识。 1.程序入参为本地文件系统路径。 2.在配置文件中searchkeywords.txt中输入要搜索的任意多个关键字 3.在配置文件中excludekeywords.txt...
使用Python处理S19文件,分析S19文件中的数据。能够很好地帮助分析S19文件
本文实例讲述了python计算文本文件行数的方法。分享给大家供大家参考。具体实现方法如下: filename = "somefile.txt" myfile = open(filename) lines = len(myfile.readlines()) print "There are %d lines in %s...
经典的使用python进行文本处理的教程。
python读取文本文件实现猜单词实现: 1、计算机必须从文本文件 gone with the wind.txt 中随机选择一个单词命名为 secretWord,单词可能包含大写和小写字母,为降低猜测难度,需要将单词转换为全部小写字母。 2、...
python文本分析与处理,比较轻量级的资源文件。 python文本分析与处理,比较轻量级的资源文件。
主要介绍了使用Python读写文本文件及编写简单的文本编辑器的方法,可以利用简单的Python代码实现编辑器中的读取清空和文本文件的新建等操作,需要的朋友可以参考下
内容概要: 这段Python代码是一个文本文件合并工具,名为 "TextFileMerger",它可以将多个文本文件的内容合并到一个新文件中。 适用人群: 适用于需要合并多个文本文件内容的个人用户、数据分析师、系统管理员、报告...
python编写的将文本文件添加标记为html文件格式,其中的simpler_markup.py是简单版本。本代码源自《python基础教程第二版》
python 处理多行多列多文件的数据 #coding=utf-8 import matplotlib.pyplot as plt filename1 = '02.txt' filename2 = '03.txt' filename3 = 'C05.txt' filename4 = 'CSS.txt' fileA = open(filename4,'w') 写入新...
使用Python进行文本挖掘分析 100份文件 使用sklearn库进行处理
如下所示: fp = file('data.txt')...以上这篇python 实现在txt指定行追加文本的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持软件开发网。 您可能感兴趣的文
用python 实现两个文本文件之间的比较,并生成可视化HTML文件。
python纯文本文件内的html标签
从Python高效处理FASTQ文件
基于python的文本挖掘应用.pdf基于python的文本挖掘应用.pdf基于python的文本挖掘应用.pdf基于python的文本挖掘应用.pdf基于python的文本挖掘应用.pdf基于python的文本挖掘应用.pdf基于python的文本挖掘应用.pdf基于...
一些常用的利用python进行文本处理的方法,数据集的处理方法