使用Python文件读写,自定义分隔符(custom delimiter)


Posted in Python onJuly 05, 2020

众所周知,python文件读取文件的时候所支持的newlines(即换行符),是指定的。这一点不管是从python的doucuments上还是在python的源码中(作者是参考了python的io版本,并没有阅读C版本),都可以看出来:

if newline is not None and not isinstance(newline, str):
 raise TypeError("illegal newline type: %r" % (type(newline),))
if newline not in (None, "", "\n", "\r", "\r\n"):
 raise ValueError("illegal newline value: %r" % (newline,))

好吧,问题来了,如果你恰好是个苦逼的生物狗,正在用python处理所谓的fastq格式的测序结果文件,每次只读一行往往不是你想要的。Ok, 我们也都知道其实这个问题在Perl里面十分好解决,无非就是重新定义下文件的分割符($/,The input record separator, newline by default. Set undef to read through the end of file.)

local $/;   # enable "slurp" mode
local $_ = <FH>; # whole file now here
s/\n[ \t]+/ /g;

简单粗暴有效!《Programming Perl》开头的那些关于什么是happiness定义看来所言非虚,所以你只要需要将$/定义为fastq格式的分隔符就ok了。

但是,如果是Python呢?(容易钻牛角尖的孩纸,又或者是不喜欢花括号的孩子…..反正就是强行高端了)。终于要进入正题了,OK,在python中又有两种方式解决这个问题,看你个人喜好选择了(当然要是有大神知道四种、五种方法,也不妨指导一下我这个小菜鸟)。

方案一的代码:

import _pyio
import io
import functools
class MyTextWrapper(_pyio.TextIOWrapper):
 def readrecod(self, sep):
   readnl, self._readnl = self._readnl, sep
   self._readtranslate = False
   self._readuniversal = False
   try:
     return self.readline()
   finally:
     self._readnl = readnl
#class MyTextWrapper(_pyio.TextIOWrapper):
# def __init__(self, *args, separator, **kwargs):
#  super().__init__(*args,**kwargs)
#  self._readnl = separator
#  self._readtranslate = False
#  self._readuniversal = False
#  print("{}:\t{}".format(self,self._readnl))

f = io.open('data',mode='rt')
#f = MyTextWrapper(f.detach(),separator = '>')
#print(f._readnl)
f = MyTextWrapper(f.detach())
records=iter(functools.partial(f.readrecod, '>'), '')
for r in records:
 print(r.strip('>'))
 print("###")

Ok,这是Python3.x中的方法(亲测),那么在Python2.x中需要改动的地方,目测好像是(没有亲测)

super(MyTextWrapper,self).__init__(*args,**kwargs)

这个方法看上去还是比较elegant,但是efficient 吗?答案恐怕并不,毕竟放弃了C模块的速度优势,但是OOP写起来还是比较舒服的。对了值得指出的Python的I/O是一个layer一个layer的累加起来的。从这里我们就能看出来。当然里面的继承关系还是值得研究一下的,从最开始的IOBase一直到最后的TextIOWrapper,这里面的故事,还是要看一看的。

方案二的代码:

#!/usr/bin/env python

def delimited(file, delimiter = '\n', bufsize = 4096):
 buf = ''
 while True:
  newbuf = file.read(bufsize)
  if not newbuf:
   yield buf
   return
  buf += newbuf
  lines = buf.split(delimiter)
  for line in lines[:-1]:
   yield line
  buf = lines[-1]

with open('data', 'rt') as f:
 lines = delimited(f, '>', bufsize = 1)
 for line in lines:
  print line,
  print '######'

Ok,这里用到了所谓的generator函数,优雅程度也还行,至于效率么,请自行比较和测试吧(毕竟好多生物程序猿是不关心效率的…..)。如此一来,比Perl多敲了好多代码,唉,怀念Perl的时代啊,简单粗暴有效,就是幸福的哲学么。

当然还有童鞋要问,那么能不能又elegant还efficient(我可是一个高端的生物程序猿,我要强行高端!)答案是有的,请用Cython! 问题又来了,都Cython了,为什么不直接用C呢?确实,C语言优美又混乱。

补充知识:Python.json.常见两个错误处理(Expecting , delimiter)(Invalid control character at)

ValueError: Invalid control character at: line 1 column 122(char 123)

出现错误的原因是字符串中包含了回车符(\r)或者换行符(\n)

解决方案:

转义

json_data = json_data.replace('\r', '\\r').replace('\n', '\\n')

使用关键字strict

json.loads(json_data, strict=False)

ValueError: Expecting , delimiter: line 13 column 650 (char 4186)

原因:json数据不合法,类似“group_buy_create_description_text”: “1. Select the blue “Buy” button to let other shoppers buy with you.这样的内容出现在json数据中。

解决方案:

将类似的情形通过正则筛选出来通过下面的方式处理。

正则表达式如下:

json_data = json_data.replace('""', '"########"')

js_str = '"[\s\S]+?":\s?"([\s\S]+?)"\}?\}?\]?,'

后续使用中发现无法匹配value为空的情况,故先做一下预处理

这个正则可以匹配到大部分的key,value中的value值,但是也有例外,暂时的处理方法是如果匹配结果中包含”{“, “}”, “[“, “]”这样的字符,说明是匹配失败结果,跳过处理。其他的使用下边的方法替换掉可能出问题的字符。

如果大家有更好的正则匹配方式,欢迎随时批评指正。

def htmlEscape(input) {
    if not input
      return input;
    input = input.replace("&", "&");
    input = input.replace("<", "<");
    input = input.replace(">", ">");
    input = input.replace(" ", " ");
    input = input.replace("'", "'");  //IE暂不支持单引号的实体名称,而支持单引号的实体编号,故单引号转义成实体编号,其它字符转义成实体名称
    input = input.replace("\"", """); //双引号也需要转义,所以加一个斜线对其进行转义
    input = input.replace("\n", "<br/>"); //不能把\n的过滤放在前面,因为还要对<和>过滤,这样就会导致<br/>失效了
    return input;
  }

以上这篇使用Python文件读写,自定义分隔符(custom delimiter)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
在Python的Bottle框架中使用微信API的示例
Apr 23 Python
python妙用之编码的转换详解
Apr 21 Python
pandas 小数位数 精度的处理方法
Jun 09 Python
Python GUI布局尺寸适配方法
Oct 11 Python
python paramiko利用sftp上传目录到远程的实例
Jan 03 Python
使用pyshp包进行shapefile文件修改的例子
Dec 06 Python
解决pyinstaller打包运行程序时出现缺少plotly库问题
Jun 02 Python
解析Tensorflow之MNIST的使用
Jun 30 Python
一文弄懂Pytorch的DataLoader, DataSet, Sampler之间的关系
Jul 03 Python
python三引号如何输入
Jul 06 Python
Django中Aggregation聚合的基本使用方法
Jul 09 Python
使用python操作lmdb对数据读取的实例
Dec 11 Python
如何清空python的变量
Jul 05 #Python
增大python字体的方法步骤
Jul 05 #Python
树莓派升级python的具体步骤
Jul 05 #Python
Python OpenCV去除字母后面的杂线操作
Jul 05 #Python
使用OpenCV去除面积较小的连通域
Jul 05 #Python
学python最电脑配置有要求么
Jul 05 #Python
浅谈OpenCV中的新函数connectedComponentsWithStats用法
Jul 05 #Python
You might like
星际流派综述
2020/03/04 星际争霸
单位速度在实战中的运用
2020/03/04 星际争霸
THINKPHP支持YAML配置文件的设置方法
2015/03/17 PHP
php获取本周星期一具体日期的方法
2015/04/20 PHP
PHP+mysql防止SQL注入的方法小结
2019/04/27 PHP
javascript中callee与caller的用法和应用场景
2010/12/08 Javascript
用Mootools获得操作索引的两种方法分享
2011/12/12 Javascript
一个JavaScript防止表单重复提交的实例
2014/10/21 Javascript
js根据鼠标移动速度背景图片自动旋转的方法
2015/02/28 Javascript
如何防止INPUT按回车自动提交表单FORM
2016/12/06 Javascript
Bootstrap实现提示框和弹出框效果
2017/01/11 Javascript
jquery实现input框获取焦点的方法
2017/02/06 Javascript
基于JS实现限时抢购倒计时间表代码
2017/05/09 Javascript
基于ES6作用域和解构赋值详解
2017/11/03 Javascript
Vue实现todolist删除功能
2018/06/26 Javascript
vue 组件销毁并重置的实现
2020/01/13 Javascript
Python读写文件方法总结
2015/06/09 Python
Python解决N阶台阶走法问题的方法分析
2017/12/28 Python
python 递归调用返回None的问题及解决方法
2020/03/16 Python
python如何求100以内的素数
2020/05/27 Python
Django 构建模板form表单的两种方法
2020/06/14 Python
Manuka Doctor美国官网:麦卢卡蜂蜜和蜂毒护肤
2016/12/25 全球购物
Tommy Hilfiger美国官网:美国高端休闲领导品牌
2019/01/14 全球购物
草莓网官网:StrawberryNET
2019/08/21 全球购物
N:Philanthropy官网:美国洛杉矶基础款服装
2020/06/09 全球购物
高中毕业生自我鉴定例文
2013/12/29 职场文书
出生医学证明样本
2014/01/17 职场文书
xxx同志考察材料
2014/02/07 职场文书
开业主持词
2014/03/21 职场文书
承诺书怎么写
2014/03/26 职场文书
《英英学古诗》教学反思
2014/04/11 职场文书
工作评语大全
2014/04/26 职场文书
摄影展策划方案
2014/06/02 职场文书
员工2014年度工作总结
2014/12/09 职场文书
2015年乡镇扶贫工作总结
2015/04/08 职场文书
nginx之queue的具体使用
2022/06/28 Servers