Python中的文本(一)

 本文主要记录和总结本人在阅读《Python标准库》一书,文本这一章节的学习和理解。




事实上在Python中,使用文本这种一些方法是特别经常使用的一件事。在一般的情况下,都会使用String这种一个类,应该算是Python中最基础的一个标准类了。



1.1 函数

string类中的capwords()和maketrans()。


capwords()的作用是将一个字符串中的全部单词的首字母大写。
maketrans()函数将创建转换表,能够translate()方法将一组字符改动成还有一组字符。这样的做法比重复调用replace()更为高效。



string中有一个叫模板的功能。

相同是用来做字符的拼接的。


高级的模板能够改动string.Template的默认语法,为此须要调整它在模板中查找变量名所使用的正則表達式。

#############################################################
#test about matetrans()
leet = string.maketrans('asdfghjk', '12345678') 
print s.translate(leet)
print s

#############################################################
#test about Template()
values = {'var':'foo'}

t=string.Template("""
Variable        : $var
Escape          : $$
Variable in text: ${var}iable
""")

print 'TEMPLATE:', t.substitute(values)

s="""
Variable        : %(var)ss

Escape          : %%
Variable in text: %(var)sssssiable
"""

print 'INTERPOLATION:', s%values


1.2 textwrap()——格式化文本段落

作用:通过调整换行符在段落中出现的位置来格式化文本。

1.3 re-正則表達式

作用:使用形式化模式搜索和改动文本。


regular expression。



1.3.1 re中搜索文本中的模式。



import re

print '-'*30
#about regular expression search()

pattern = 'this'
text='Does this text match the pattern?'
 
match = re.search(pattern, text)
 
s=match.start()
e=match.end()
 
print 'Dound "%s" 
in "%s" 
from %d to %d ("%s")' % 
       (match.re.pattern,match.string,s,e,text[s:e])
        
#start()和end()方法能够给出字符串中对应的索引。


1.3.2 编译正則表達式

re包括一些模块级的函数。用于处理作为文本字符串的正則表達式。对于频繁使用的表达式,编译这些表达式会更加的高效。

compile()函数会把一个表达式字符串转换成为一个RegexObject。



print '-'*30
#about the Compile()
regexes=[re.compile(p)
         for p in ['this','that']
         ]
text='Does this text match the pattern?'
 
print 'Text: %r
' % text
 
for regex in regexes:
    print 'seeking "%s" ->' % regex.pattern
     
    if regex.search(text):
        print 'match!'
    else:
        print 'no match!'
  

模块级函数会维护已编译表达式的一个缓存。可是这个缓存的大小是有限的。直接使用已编译的表达式能够避免缓存查找开销。使用已编译表达式的还有一个优点是,把编译的过程进行了提前。在某种程度上优化了程序执行过程中的效率。

1.3.3 多重匹配

search()在前面中,是用来查找文本字符串中的单个实例。

findall()函数会返回输入中与模式匹配的,而不重叠的全部子串。



print '-'*30
#about the findall()
text = 'bbbbbababbababbabbbaba'
pattern = 'ba'

for match in re.findall(pattern, text):
    print match

print '-'*30
#about the finditer()
#finditer会返回一个迭代器,能够生成match实例。而不像findall()是直接返回的字符串。

text='aaaadaaaaadadadada' pattern='da' for match in re.finditer(pattern,text): s=match.start() e=match.end() print 'Found "%s" at %d:%d' % (text[s:e],s,e)


1.3.4 模式语法

Python的正則表達式的模式语法。

1.3.5 限制搜索

假设提前已经知道仅仅须要搜索整个输入的一个子集,能够告诉re先知搜索范围,从而进一步约束正則表達式。


print '-'*30
#一种iterall()的不太高效的实现方式。

text='this is some text -- with punctuation.' pattern=re.compile(r'w*isw*') print 'text:', text pos=0 while True: match=pattern.search(text,pos) print match if not match: break s=match.start() e=match.end() print s,e print '%d: %d = "%s"' % (s,e-1,text[s:e]) pos=e


原文地址:https://www.cnblogs.com/yjbjingcha/p/7095807.html