使用python中的列表查找和替换csv字符串 [英] Find and replace csv strings using a list in python

查看:1839
本文介绍了使用python中的列表查找和替换csv字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这么多。

import csv

ifile = open('file', 'rb')
reader = csv.reader(ifile,delimiter='\t')
ofile = open('file', 'wb')
writer = csv.writer(ofile, delimiter='\t')


findlist = ['A', 'G', 'C', 'T', 'Y', 'R', 'W', 'S', 'K', 'M', 'X', 'N', '-']
replacelist = ['AA', 'GG', 'CC', 'TT', 'CT', 'AG', 'AT', 'GC', 'TG', 'CA', 
'NN', 'NN', '-']

rep = dict(zip(findlist, replacelist))

def findReplace(find, replace):
    s = ifile.read()
    s = s.replace(find, replace)
    ofile.write(s)

for item in findlist:
    findReplace(item, rep[item])

ifile.close()
ofile.close() 

它是用AA取代A。然而我想要的是用 replacelist 中的字母替换所有的字母。我对python很新,也不知道为什么它不会替换一切。

What it does is replaced the A with AA. However what I want is to replace all of the letters with the ones in the replacelist. I am very new to python and can't quite figure out why its not replacing everything.

HE670865    399908  N   N   N   N   N
HE670865    399910  N   N   N   N   N
HE670865    399945  T   T   N   T   T
HE670865    399951  R   R   N   A   A
HE670865    399957  A   A   N   A   A
HE670865    399978  C   C   C   M   C
HE670865    399980  C   C   C   C   C
HE670865    399982  T   T   T   T   K
HE670865    399984  C   C   C   C   C


HE670865    399908  N   N   N   N   N
HE670865    399910  N   N   N   N   N
HE670865    399945  T   T   N   T   T
HE670865    399951  R   R   N   AA  AA
HE670865    399957  AA  AA  N   AA  AA
HE670865    399978  C   C   C   M   C
HE670865    399980  C   C   C   C   C
HE670865    399982  T   T   T   T   K
HE670865    399984  C   C   C   C   C


推荐答案

这是因为你在循环中阅读和写作。

It is because you are reading and writing inside the loop.

rep = dict(zip(findlist, replacelist))

s = ifile.read()
for item in findlist:
    s = s.replace(item, rep[item])
ofile.write(s)

更易读(更简洁),而不使用不必要的 dict

Also, I think your code would be more readable (and more concise), without using the unnecessary dict.

s = ifile.read()
for item, replacement in zip(findlist, replacelist):
    s = s.replace(item, replacement)
ofile.write(s)

这篇关于使用python中的列表查找和替换csv字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆