7.1.7 文件内容的搜索和替换

文件内容的搜索和替换可以结合前面学习的字符串查找和替换来实现。例如,从hello.txt文件中查找字符串“hello”,并统计“hello”出现的次数。hello.txt文件如下所示。


1 hello world
3 hello hello China

下面【例7-4】这段代码从hello.txt中统计字符串“hello”的个数。

【例7-4.py】


01     # 文件的查找
02     import re               # 导入re模块
03
04     f1 = open("hello.txt", "r")
05     count = 0
06     for s in f1.readlines():
07         li = re.findall("hello", s)
08         if len(li) > 0:
09             count = count + li.count("hello")
10     print ("查找到" + str(count) + "个hello")
11     f1.close()

【代码说明】

·第5行代码定义变量count,用于计算字符串“hello”出现的次数。

·第6行代码每次从文件hello.txt中读取1行到变量s。

·第7行代码调用re模块的函数findall()查询变量s,把查找的结果存储到列表li中。

·第8行代码,如果列表中的元素个数大于0,则表示查找到字符串“hello”。

·第9行代码调用列表的count()方法,统计当前列表中“hello”出现的次数。

·第10行代码输出结果:


查找到3个hello

下面这段代码把hello.txt中的字符串“hello”全部替换为“hi”,并把结果保持到文件hello2.txt中。


01     # 文件的替换
02     f1 = open("hello.txt", "r")
03     f2 = open("hello2.txt", "w")
04     for s in f1.readlines():
05         f2.write(s.replace("hello", "hi"))
06     f1.close()
07     f2.close()

【代码说明】

·第4行代码从hello.txt中读取每行内容到变量s中。

·第5行代码先使用replace()把变量s中的“hello”替换为“hi”,然后把结果写入文件hello2.txt中。文件hello2.txt的内容如下所示。


1 hi world
3 hi hi China