使用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的id()函数介绍
Feb 10 Python
python通过ssh-powershell监控windows的方法
Jun 02 Python
Python写入数据到MP3文件中的方法
Jul 10 Python
matplotlib绘制动画代码示例
Jan 02 Python
python如何重载模块实例解析
Jan 25 Python
Python基于socket模块实现UDP通信功能示例
Apr 10 Python
Python实现string字符串连接的方法总结【8种方式】
Jul 06 Python
python获取微信小程序手机号并绑定遇到的坑
Nov 19 Python
python区块及区块链的开发详解
Jul 03 Python
Python迭代器协议及for循环工作机制详解
Jul 14 Python
python 进阶学习之python装饰器小结
Sep 04 Python
Python Matplotlib绘制等高线图与渐变色扇形图
Apr 14 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
Win9x/ME下Apache+PHP安装配置
2006/10/09 PHP
Redis在Laravel项目中的应用实例详解
2017/08/11 PHP
ecshop添加菜单及权限分配问题
2017/11/21 PHP
在IE6下发生Internet Explorer cannot open the Internet site错误
2010/06/21 Javascript
$.getJSON在IE下失效的原因分析及解决方法
2013/06/16 Javascript
JavaScript获取当前日期是星期几的方法
2015/04/06 Javascript
jquery实现可自动收缩的TAB网页选项卡代码
2015/09/06 Javascript
js中实现字符串和数组的相互转化详解
2016/01/24 Javascript
jstree创建无限分级树的方法【基于ajax动态创建子节点】
2016/10/25 Javascript
EasyUI 中combotree 默认不能选择父节点的实现方法
2016/11/07 Javascript
JS实现的几个常用算法
2016/11/12 Javascript
基于jQuery实现数字滚动效果
2017/01/16 Javascript
详解bootstrap导航栏.nav与.navbar区别
2017/11/23 Javascript
详解Vue中数组和对象更改后视图不刷新的问题
2018/09/21 Javascript
详解Vue This$Store总结
2018/12/17 Javascript
JavaScript表格隔行变色和Tab标签页特效示例【附jQuery版】
2019/07/11 jQuery
浅谈React中组件逻辑复用的那些事儿
2020/05/21 Javascript
小程序实现列表展开收起效果
2020/07/29 Javascript
[36:02]DOTA2上海特级锦标赛D组小组赛#2 Liquid VS VP第一局
2016/02/28 DOTA
Python多继承原理与用法示例
2018/08/23 Python
python使用selenium登录QQ邮箱(附带滑动解锁)
2019/01/23 Python
Python魔法方法详解
2019/02/13 Python
学习python可以干什么
2019/02/26 Python
tensorflow指定GPU与动态分配GPU memory设置
2020/02/03 Python
Python sep参数使用方法详解
2020/02/12 Python
Django模板获取field的verbose_name实例
2020/05/19 Python
利用css3-animation实现逐帧动画效果
2016/03/10 HTML / CSS
加拿大著名时装品牌:SOIA & KYO
2016/08/23 全球购物
黑猩猩商店:The Chimp Store
2020/02/12 全球购物
俄罗斯隐形眼镜和眼镜在线商店:Cronos
2020/06/02 全球购物
简述Linux文件系统通过i节点把文件的逻辑结构和物理结构转换的工作过程
2016/01/06 面试题
中学生励志演讲稿
2014/04/26 职场文书
小学班主任评语
2014/12/29 职场文书
西双版纳导游词
2015/02/03 职场文书
行政助理岗位职责
2015/02/10 职场文书
2019年励志签名:致拼搏路上的自己
2019/10/11 职场文书