pythonextractall
‘壹’ python 数据处理(三十六)—— 文本数据处理(续)
可以使用 [] 符号直接按位置进行索引,如果索引超过字符串的长度,结果将是 NaN
在 0.23 版本之前, extract 方法的参数 expand 默认为 False 。当 expand=False 时, expand 会根据正则表达式模式返回一个 Series 、 Index 或 DataFrame
当 expand=True 时,它总是返回一个 DataFrame ,这种方式更加符合用户的需求,从 0.23.0 版本开始就是默认的
extract 方法接受一个至少包含一个捕获组的正则表达式
如果是包含多个组的正则表达式将返回一个 DataFrame ,每个捕获组是一列
未匹配的行会填充 NaN ,可以从混乱的字符串序列中提取出有规则的信息。
对于命名分组
对于可选的分组
注意 :正则表达式中的任何捕获组名称都将用作列名,否则将使用捕获组号
如果 expand=True ,则返回一个 DataFrame
如果 expand=False ,则返回一个 Series
对于索引,如果 expand=True ,且只有一个捕获组则返回一个只有一列的 DataFrame
此时,如果 expand=False 将会返回一个 Index
对于索引,正则表达式设置多个分组将返回 DataFrame
如果 expand=False 将会抛出 ValueError 异常
对于 extract 只返回第一个匹配项
与 extract 不同, extractall 方法返回每个匹配项,其结果始终是具有 MultiIndex 的 DataFrame 。
MultiIndex 的最后一级名为 match ,标示的是匹配的顺序
对于只有一个匹配的 Series
extractall(pat).xs(0, level='match') 与 extract(pat) 的结果一致
Index 也支持 .str.extractall ,它返回一个 DataFrame ,其结果与 Series.str 相同。
您可以检查字符串元素中是否包含正则匹配模式
或者字符串元素是否与模式匹配
而在 1.1.0 版本中
注意 :
match 、 fullmatch 和 contains 之间的区别是:
这三个函数于 re 模块的 re.fullmatch 、 re.match 和 re.search 对应
像 match , fullmatch , contains , startswith 和 endswith 有一个额外的 na 参数,用于将缺失值替换为 True 或 False
您可以从字符串行中提取指标变量。例如,如果使用 '|' 分隔的字符串
字符串 Index 也支持 get_mmies ,它返回一个 MultiIndex
‘贰’ python怎样解压.tar.gz的文件
linux:
os.system('tar zxf %s' % filename )
window:
import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()
‘叁’ python 3.2版本 解压rar/zip到指定目录
python没有rar模块的
‘肆’ Python:invalid syntax的问题
我给你改了一下:
importzipfile
fromthreadingimportThread
defextractFile(zFile,password):
try:
zFile.extractall(pwd=password.encode())
print('password:'+password+' ')
zFile.close()
exceptExceptionase:
pass
defmain():
zFile=zipfile.ZipFile('evil.zip')
passFile=open('dict.txt')
lines=passFile.readlines()
passFile.close()
forlineinlines:
password=line.strip(' ')
t=Thread(target=extractFile,args=(zFile,password))
t.start()
if__name__=='__main__':
main()
要学习异常处理,参考这个教程吧:刘江的博客及教程
‘伍’ python中的zipfile
python中的zipfile模块是用于解压/压缩zip文件的,压缩a.txt为a.zip,从b.zip解压出b.txt(假设它们都放在d:\,且b.zip中只有b.txt)示范代码如下5行:
from os import chdir;
from zipfile import ZipFile;
chdir("d:/");
with Zipfile("d:/b.zip","r") as zipf:zipf.extractall();
with Zipfile("d:/a.zip","w") as zipf:zipf.write("d:/a.txt");