2

到目前为止我有这个。

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() 

它所做的是将 A 替换为 AA。但是我想要的是将所有字母替换为replacelist. 我对 python 很陌生,不能完全弄清楚为什么它不能替换所有东西。

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
4

1 回答 1

5

这是因为你在循环内读写。

rep = dict(zip(findlist, replacelist))

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

另外,我认为您的代码将更具可读性(并且更简洁),而无需使用不必要的dict.

s = ifile.read()
for item, replacement in zip(findlist, replacelist):
    s = s.replace(item, replacement)
ofile.write(s)
于 2013-11-03T00:55:55.760 回答