一、正则表达式
1.用法:使用Python的re模块,首先用re.compile() 函数,将正则表达式的字符串形式编译为Pattern实例,然后通过Pattern实例处理文本并获得匹配结果(Match实例),再通过Match实例做其他操作。
2.re模块中的match方法:只匹配字符串开始处的字符。3.re模块中的search方法:会匹配整个字符串。'''
# 1
pattern = re.compile('[a-zA-Z]')
match = pattern.findall('ddhfsaqugfa3412hdh21hhdGAAASAA')
print(match)
# 2
print(re.match('\d0','30ddd'))
# 3
print(re.search('\d0','ddd30ddd40ffff50hhh'))
# 1
pattern = re.compile('[a-zA-Z]')
match = pattern.findall('ddhfsaqddDDa3412h21hdGAA')
print(match)
# 2
print(re.match('\d0','30ddd'))
# 3
print(re.search('\d0','ddd30ddd40ffff50hhh'))
二、文件处理
1.打开文件:用open函数,参数为文件路径和打开方式,打开文件返回为fileObject类型
2.读取文件:read函数来处理fileObject类型文件
3.open(path,'x') x = w 是写(原文覆盖),x = r 是读 x = a 写(原文后面追加)
4.换行写入:在要写入的字符串前加/n
5:读写特定编码的文章:open(path,'r',encoding='gbk/utf-8')
6:读写一行:readline() readlines() writelines()
7:工程中出现异常,和安全性考虑:用with
path ='C://Text2.txt'
path1 ='C://Text3.txt'
# 1
file =open(path,'a')
# 2 3
file.write('嘻嘻嘻嘻')
file =open(path,'r')
print(file.read())
file =open(path,'a')
# 4
print(file.write('\njjjjj'))
file =open(path1,'w')
str_list = ['hello\n','world\n','hello hhh\n']
# 6
new_file = file.writelines(str_list)
print('new_file:',new_file)
file =open(path1,'r')
print('file.read:',file.read())
file =open(path1,'r')
print('file.readlines:',file.readlines())
path2 ='C://Text4.txt'
# 7
with open(path2,'w')as f:
print('write length:',f.write('hello world'))
path ='C:/Text2.txt'
path1 ='C:/Text3.txt'
# 1
file =open(path,'a')
# 2 3
file.write('嘻嘻嘻嘻')
file =open(path,'r')
print(file.read())
file =open(path,'a')
# 4
print(file.write('\njjjjj'))
file =open(path1,'w')
str_list = ['hello\n','world\n','hello hhh\n']
# 6
new_file = file.writelines(str_list)
print('new_file:',new_file)
file =open(path1,'r')
print('file.read:',file.read())
file =open(path1,'r')
print('file.readlines:',file.readlines())
path2 ='C:/Text4.txt'
# 7
withopen(path2,'w')asf:
print('write length:',f.write('hello world'))
今天先放点最简单的内容,以后用户多的话可能就每天更新了。
领取专属 10元无门槛券
私享最新 技术干货