python 大文本文件 解析、入库并转换后写入新文件

tim_spac 2011-12-20 10:42:50
#!/usr/bin/python2.7
# encoding: utf-8

''' 处理某大文本文件,结果同时写入数据库及文本文件 '''

import re

from mylib.dbi import DataBaseInterface
from app_common import config

class Klass(object):

FMT = '%(id)d, %(name)s'

def __init__(self, **kwg):
self.id = dict(kwg).get('id')
self.name = dict(kwg).get('name')

def __str__(self):
''' 按指定格式将对象属性格式化为字符串 '''
return self.FMT % self.__dict__

def sqltuple(self):
''' 按指定的顺序输出对象属性元组 '''
return tuple([self.id, self.name])

patt = re.compile(r'^(?P<id>\d+)\t(?P<name>.*)[\s\r\n]+?$', re.I|re.X|re.U)

def process(line):
''' 按预定的格式解析行,生成对象实例 '''
m = patt.match(line)
return None if not m else Klass(**m.groupdict())

dbi = DataBaseInterface(**config)
dbi.open()

# dbi.batch是DataBaseInterface的方法:
# 用dbi.conn.executemany执行批量数据操作
# 支持 with 自动初始化-关闭,支持缓冲空间自动控制
buff = dbi.batch(insertsql)
src = open(srcfilename,'r')
wrt = open(wrtfilename, 'w')

with src, wrt, buff:
for ln in handle:
instance = process(ln)
if instance:
wrt.write('%s\n'%instance)
buff.append(instance.sqltuple())

dbi.close()


以上代码从目前可以正常工作的程序中简化而来。
在其运行完后,由其它方式将新写的文件移入压缩包。
现在想进一步优化一下:新文件直接写入压缩包内(zip/gz/..均可);
我知道的一种方式是先将要写入的文本保存与内存,然后一次性写入压缩包中;
... 问题在于文件很大,不宜如此操作。

有什么方式可以这样:
wrt = SomePackageMethord.open(wrtfilename, 'w', compressmode)
或:
package = SomePackageMethord(packagefile, 'w', compressmode)
wrt = package.write(arc_filename)
?


特请支援。
...全文
633 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
iambic 2011-12-20
  • 打赏
  • 举报
回复
zipfile不支持。看下:
http://stackoverflow.com/questions/297345/create-a-zip-file-from-a-generator-in-python
tim_spac 2011-12-20
  • 打赏
  • 举报
回复
zipfile的write方法是将一个已存在的文件filename写到压缩包中并重命名为arcname;
zipfile的writestr方法是将一个缓冲区bytes的数据写入到压缩包中并命名为arcname;

1. 第一种方法目前在用(是另外的模块),将本脚本运行后生成的文件打包,现在想不在磁盘上生成文件就直接写入压缩包中;
2. 第二种方法是一次性写入,若第二次写入则先前的内容将被丢掉;若将数据先保存到内存,处理完成后一次写入可以实现预期,但当数据量超大时 ... :(
askandstudy 2011-12-20
  • 打赏
  • 举报
回复
[Quote=引用楼主 tim_spac 的回复:]
以上代码从目前可以正常工作的程序中简化而来。
在其运行完后,由其它方式将新写的文件移入压缩包。
现在想进一步优化一下:新文件直接写入压缩包内(zip/gz/..均可);
我知道的一种方式是先将要写入的文本保存与内存,然后一次性写入压缩包中;
... 问题在于文件很大,不宜如此操作。

有什么方式可以这样:
wrt = SomePackageMethord.open(wrtfilename, 'w', compressmode)
或:
package = SomePackageMethord(packagefile, 'w', compressmode)
wrt = package.write(arc_filename)
[/Quote]

没怎么看懂楼主的意思,我用过一下zipfile模块,它有write和writestr方法,还有些别的方法,不知道是不是你需要的。


write(filename, [arcname, [compress_type]])
Write the file named filename to the archive, giving it the archive name arcname (by default, this will
be the same as filename, but without a drive letter and with leading path separators removed). If given,
compress_type overrides the value given for the compression parameter to the constructor for the new entry.
The archive must be open with mode ’w’ or ’a’ – calling write() on a ZipFile created with mode ’r’
will raise a RuntimeError. Calling write() on a closed ZipFile will raise a RuntimeError.
Note: There is no official file name encoding for ZIP files. If you have unicode file names, you must
convert them to byte strings in your desired encoding before passing them to write(). WinZip interprets
all file names as encoded in CP437, also known as DOS Latin.
Note: Archive names should be relative to the archive root, that is, they should not start with a path
separator.
Note: If arcname (or filename, if arcname is not given) contains a null byte, the name of the file in
the archive will be truncated at the null byte.
writestr(zinfo_or_arcname, bytes, [compress_type])
Write the string bytes to the archive; zinfo_or_arcname is either the file name it will be given in the archive,
or a ZipInfo instance. If it’s an instance, at least the filename, date, and time must be given. If it’s a
name, the date and time is set to the current date and time. The archive must be opened with mode ’w’ or
’a’ – calling writestr() on a ZipFile created with mode ’r’ will raise a RuntimeError. Calling
writestr() on a closed ZipFile will raise a RuntimeError.
If given, compress_type overrides the value given for the compression parameter to the constructor for the
new entry, or in the zinfo_or_arcname (if that is a ZipInfo instance).
Note: When passing a ZipInfo instance as the zinfo_or_acrname parameter, the compression method
used will be that specified in the compress_type member of the given ZipInfo instance. By default, the
ZipInfo constructor sets this member to ZIP_STORED. Changed in version 2.7: The compression_type
argument.


具体描述看库文档吧
tim_spac 2011-12-20
  • 打赏
  • 举报
回复
谢谢各位。决定采用gzip.
内容概要:本文围绕“非线性流量的数据驱动Koopman模型预测控制研究”展开,提出一种基于数据驱动的Koopman算子理论方法,用于构建非线性系统的线性化状态空间模型,并结合模型预测控制(MPC)实现对复杂非线性系统的高效控制。研究通过引入扩展动态模态分解(EDMD)等观测函数,将非线性动力学映射至高维特征空间,在该空间中实现近似线性化表征,进而融合线性MPC框架进行优化求解。全文系统阐述了Koopman算子的数学基础、隐式线性化机制及在非线性流量控制中的建模流程,并通过Matlab代码完成了算法实现与仿真实验,验证了该方法在处理无精确物理模型、强非线性、时变动态系统中的有效性与鲁棒性,尤其适用于工业流程控制、能源系统调度等实际工程场景。; 适合人群:具备自动控制理论、非线性系统分析基础,熟悉Matlab编程,从事控制工程、系统辨识、智能优化、能源系统建模等方向的研究生、科研人员及工程技术人员。; 使用场景及目标:①应用于难以建立精确数学模型的复杂非线性系统(如流体动力系统、电力电子系统、机器人动力学等)的建模与实时控制;②实现数据驱动下的模型预测控制,提升系统响应速度与控制精度;③为先进控制策略(如MPC)提供一种可行的线性化建模范式,推动现代控制理论与数据科学、机器学习的深度融合。; 阅读建议:建议读者结合提供的Matlab代码深入理解Koopman方法的具体实现过程,重点关注观测函数构造、核函数选择、矩阵逼近、降维处理及MPC控制器设计等关键技术环节,并尝试将其迁移至其他非线性系统中进行复现实验与性能对比,以全面掌握其适用范围与局限性。
内容概要:本文详细介绍了一种基于Simulink的光伏储能单相逆变器并网仿真模型,系统涵盖了光伏阵列、储能单元、DC-AC单相逆变器及并网接口的完整结构,重点实现了储能环节的能量管理与逆变器并网控制策略的建模仿真。通过Simulink平台构建系统模型,验证了逆变器输出电能质量、并网稳定性以及控制系统的动态响应性能,采用SPWM调制、PI闭环控制等关键技术,确保并网电流与电网电压同频同相,满足并网电能质量要求。该模型不仅可用于分布式能源系统的仿真研究,还可作为能源并网技术的教学与工程实践工具。; 适合人群:电气工程、自动化、能源科学与工程等相关专业的高校本科生、研究生、科研人员,以及从事光伏发电系统设计、储能控制与并网技术研发的工程技术人员。; 使用场景及目标:①深入理解光伏储能系统中能量转换、存储与并网控制的整体工作原理;②支持课程设计、毕业设计或科研项目中对单相逆变器控制策略(如SPWM、PI调节、锁相技术等)的仿真验证与参数优化;③为后续研究更复杂的控制算法(如MPPT、低电压穿越、谐波抑制等)提供可扩展的仿真基础平台。; 阅读建议:建议结合MATLAB/Simulink环境动手搭建与调试模型,逐步理解各模块(如光伏建模、储能充放电控制、逆变器驱动、锁相环、PI调节器等)的功能与交互关系,重点关注控制系统的设计逻辑与参数整定过程,并可通过修改负载条件或电网参数测试系统鲁棒性,为进一步拓展至三相系统或多机并网场景奠定基础。

37,741

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧