统计字符串中关键字出现过的次数:
#coding=utf-8
import re
String_1 ='Python由荷兰数学家吉多·范罗苏姆于二十世纪九十年代初设计。Python提供了高效的高级数据结构,还能简单有效地面向对象编程。'
#统计字符串中关键字'Python'出现过的次数:
Key_1 = 'Python'
Result_1 = re.findall(Key_1,String_1)
print(len(Result_1))
#统计字符串中关键字'数学'出现过的次数:
Result_1 = String_1.count('数学')
print(Result_1)
#统计字符串中关键字'zhuohua'出现过的次数:
Key_1 = 'zhuohua'
Result_1 = String_1.count(Key_1)
print(Result_1)
脚本运行的结果:(区分英文字母大小写)
C:\Users\jacky\Desktop>python xx.py
2
1
0
C:\Users\jacky\Desktop>
############
统计文件内容中关键字出现过的次数:
#coding=utf-8
import re
def func1(Path_1,Key_1):
f_name = open(Path_1,'r') #打开文件,读取内容
#re.M:多行模式
#re.I:忽略英文字母的大小写
Result_1 = re.findall(Key_1,f_name.read(),re.M|re.I)
Result_2 = len(Result_1)
print(f"关键字'{Key_1}'出现了 {Result_2} 次")
f_name.close() #关闭文件
if __name__ == '__main__':
Path_1 = "D:/share/Python3搭建HTTP文件服务器.txt"
Key_1 = "Warning" #关键字
func1(Path_1,Key_1)
脚本运行的结果:(文件内容中没有关键字时)
C:\Users\jacky\Desktop>python xx.py
关键字'Warning'出现了 0 次
C:\Users\jacky\Desktop>
脚本运行的结果:(文件内容中关键字出现过一次时)
C:\Users\jacky\Desktop>python xx.py
关键字'Warning'出现了 1 次
C:\Users\jacky\Desktop>
脚本运行的结果:(文件内容中关键字出现过三次时)
C:\Users\jacky\Desktop>python xx.py
关键字'Warning'出现了 3 次
C:\Users\jacky\Desktop>
############
检测多个文件的内容中是否包含关键字:
#coding=utf-8
import re
def func1(Path_1,Key_1):
f_name = open(Path_1,'r') #打开文件,读取内容
try:
#re.M:多行模式
#re.I:忽略英文字母的大小写
Result_1 = re.search(Key_1,f_name.read(),re.M|re.I).span()[0]
except:
func3(Path_1,Key_1)
else:
func2(Path_1,Key_1)
finally:
f_name.close() #关闭文件
def func2(Path_1,Key_1):
print(f"异常,文件'{Path_1}'里有关键字'{Key_1}'")
def func3(Path_1,Key_1):
print(f"正常,文件'{Path_1}'里没有关键字'{Key_1}'")
if __name__ == '__main__':
Path_1 = "D:\\share\\Python3搭建HTTP文件服务器.txt"
Key_1 = "Warning" #关键字
func1(Path_1,Key_1)
Path_1 = "D:\\share\\Python3搭建FTP文件服务器.log"
Key_1 = "错误" #关键字
func1(Path_1,Key_1)
脚本运行的结果:(文件Python3搭建HTTP文件服务器.txt、Python3搭建FTP文件服务器.log都没有关键字时)
C:\Users\jacky\Desktop>python xx.py
正常,文件'D:\share\Python3搭建HTTP文件服务器.txt'里没有关键字'Warning'
正常,文件'D:\share\Python3搭建FTP文件服务器.log'里没有关键字'错误'
C:\Users\jacky\Desktop>
脚本运行的结果:(文件Python3搭建HTTP文件服务器.txt有关键字、Python3搭建FTP文件服务器.log没有关键字时)
C:\Users\jacky\Desktop>python xx.py
异常,文件'D:\share\Python3搭建HTTP文件服务器.txt'里有关键字'Warning'
正常,文件'D:\share\Python3搭建FTP文件服务器.log'里没有关键字'错误'
C:\Users\jacky\Desktop>
脚本运行的结果:(文件Python3搭建HTTP文件服务器.txt没有关键字、Python3搭建FTP文件服务器.log有关键字时)
C:\Users\jacky\Desktop>python xx.py
正常,文件'D:\share\Python3搭建HTTP文件服务器.txt'里没有关键字'Warning'
异常,文件'D:\share\Python3搭建FTP文件服务器.log'里有关键字'错误'
C:\Users\jacky\Desktop>
脚本运行的结果:(文件Python3搭建HTTP文件服务器.txt、Python3搭建FTP文件服务器.log都有关键字时)
C:\Users\jacky\Desktop>python xx.py
异常,文件'D:\share\Python3搭建HTTP文件服务器.txt'里有关键字'Warning'
异常,文件'D:\share\Python3搭建FTP文件服务器.log'里有关键字'错误'
C:\Users\jacky\Desktop>
相关文章:
正则表达式
字典
try语句
自定义函数 |