正则表达式之模糊匹配详解
regular expression,缩写成regex
这里以.txt类型的诗 the man from snowy river为文本(可网上查找)
首先读取文本
import re ##正则的库
text = ''
file = open('data\poem.txt')
for line in file:
text = text + line
file.close()
print(text)
查找这首诗中有多少个单词to
result = re.findall(' to ',text) ##完整的单词,前后需要加空格
print(len(result))
模糊匹配
查找以a开头的三个字母的单词
前面都是思路历程,完整代码请看最后一段
result = re.findall('a..',text)
print(result)
这种情况下,a…可以匹配所有的东西,包括空格,逗号。并不是以a开头的三个字母的单词。
因此,限定第二、三个位置为a-z的字母:
result = re.findall(' a[a-z][a-z] ',text) ##左右边加空格
print(result)
##加*,前后可以有空格,也可以没有空格,也可以有很多个空格,就把开头给选出来了,比如句首开头All
result = re.findall(' *([Aa][a-z][a-z]) ',text)
##[Aa]代表第一个字母可以是A,也可以是a
result = set(result) ##去除重复的单词
print(result)
结果
{‘air’, ‘ads’, ‘ash’, ‘ack’, ‘all’, ‘ath’, ‘And’, ‘arp’, ‘ard’, ‘ant’, ‘ade’, ‘are’, ‘ake’, ‘ain’, ‘ame’, ‘aze’, ‘and’, ‘afe’, ‘any’, ‘ast’, ‘ave’, ‘age’, ‘als’, ‘ags’, ‘ace’, ‘All’, ‘ars’}
发现,比如safe,后三个字母满足上述代码的条件
##分成两种情况进行过滤
result = re.findall(' (a[a-z][a-z]) |(A[a-z][a-z]) ',text)
##a是前后都有空格,A是前面没有空格,后面有空格
result = set(result)
print(result)
结果:
{(‘are’, ‘’), (’’, ‘And’), (‘ash’, ‘’), (‘air’, ‘’), (’’, ‘All’), (‘all’, ‘’), (‘and’, ‘’)
##只选出单词
result = re.findall(' (a[a-z][a-z]) |(A[a-z][a-z]) ',text)
##a是前后都有空格,A是前面没有空格,后面有空格
result = set(result)
final_result = set()
for pair in result:
if pair[0] not in final_result:
final_result.add(pair[0])
if pair[1] not in final_result:
final_result.add(pair[1])
final_result.remove('')
print(final_result)
其他功能,后面再补呀。
本文详细解析Python中正则表达式的模糊匹配,通过实例演示如何查找以a开头的三个字母的单词,避免匹配到不期望的结果。文章最后展示了实际运行的代码输出,包括匹配到的单词列表及其相邻关系。
772

被折叠的 条评论
为什么被折叠?



