正则表达式 找log中的name
# 求各类文件大小的总和,并写到新的文件中 import re # 定义一个字典做文件类型的归类 dict_file={} with open('log.txt') as files,open('d:/1/new2.txt','w') as f: for file in files: # 获得字符串 file_type = re.findall(f'\.\w+',file)[0]#是list格式的值 ['.jpg'] 需要取小标为0 file_size = int(file.split(' ')[1])# 截取字符串后获得列表['13f20189111090619/j4mxbEivh.json', '2990', 'Fpq-3y13Yr1CadNrJVSDnpeRhot'] if file_type not in dict_file: dict_file[file_type] = file_size else: dict_file[file_type]+= file_size print(dict_file)# {'.jpeg': 226396, '.json': 181188, '.jpg': 136334} f.write(str(dict_file))
import re file1=(open('1.txt').readlines())
'''
A girl come in, the name is Jack, evel 955;
A old lady come in, the name is Mary,level 94454;
A pretty boy come in, the name is Patrick, level 194;
''' print(file1) for i in file1: # 通过正则获得全部的name name = re.findall(r'the name is ([a-zA-Z\s]+)', i)#([a-zA-Z\s]+)仅匹配字母和空格的非单个字母的单词
print(name)
import re
str3='runoob 123 google 456 999 777' str4='set width=20 and height=10' result3 = re.findall(r'\d+',str3) result33 = re.findall(r'(\d+)',str3) result4 = re.findall(r'(\w+)=(\d+)',str4) print(result3) print(result33) print(result4) text = "A girl come in, the name is Jack, evel 955; A old lady come in, the name is Mary,level 94454; A pretty boy come in, the name is Patrick, level 194;" names = re.findall(r'the name is (\w+)', text) print(names) ''' ['123', '456', '999', '777'] ['123', '456', '999', '777'] [('width', '20'), ('height', '10')] ['Jack', 'Mary', 'Patrick'] '''
1.txt里的内容
A girl come in, the name is Jack, evel 955; A old lady come in, the name is Mary,level 94454; A pretty boy come in, the name is Patrick, level 194;
# 第一步 从txt中获取名字
file_path='1.txt' with open(file_path,'r') as f: # 按行读 返回列表 list1=f.read().splitlines() # 第二步 对列表中的每一个元素做拆分 # 找到name的值 def get_name(list1): for item in list1: name = item.split(',')[1].split(' ')[-1:] print(name) get_name(list1)
import re text = "A girl come in, the name is Jack, evel 955;
A old lady come in, the name is Mary,level 94454;
A pretty boy come in, the name is Patrick, level 194;" names = re.findall(r'the name is (\w+)', text) print(names)
str4='set width=20 and height=10' result4 = re.findall(r'(\w+)=(\d+)',str4) ''' [('width', '20'), ('height', '10')] '''