从Python调用gawk
我正在尝试通过这种方式从Python调用gawk(GNU版本的AWK)。
import os
import string
import codecs
ligand_file=open( "2WTKA_ab.txt", "r" ) #Open the receptor.txt file
ligand_lines=ligand_file.readlines() # Read all the lines into the array
ligand_lines=map( string.strip, ligand_lines )
ligand_file.close()
for i in ligand_lines:
os.system ( " gawk %s %s"%( "'{if ($2==""i"") print $0}'", 'unique_count_a_from_ac.txt' ) )
我的问题是,“i”没有被它所代表的值替换。这个“i”代表的值是一个整数,而不是字符串。我该如何解决这个问题呢?
2 个回答
4
这种方法检查文件里有没有东西既不方便又很麻烦。想象一下,如果你有1000行数据,你就得调用gawk 1000次,这样效率超级低下。既然你在用Python,那就直接用Python来处理吧。
....
ligand_file=open( "2WTKA_ab.txt", "r" ) #Open the receptor.txt file
ligand_lines=ligand_file.readlines() # Read all the lines into the array
ligand_lines=map( str.strip, ligand_lines )
ligand_file.close()
for line in open("unique_count_a_from_ac.txt"):
sline=line.strip().split()
if sline[1] in ligand_lines:
print line.rstrip()
如果不一定要用Python的话,你也可以用这个一行代码来解决。
gawk 'FNR==NR{a[$0]; next}($2 in a)' 2WTKA_ab.txt unique_count_a_from_ac.txt
1
你的问题出在引号的使用上。在Python中,像"some test "" with quotes"
这样的写法是不会给你返回一个引号的。试试下面这个方法:
os.system('''gawk '{if ($2=="%s") print $0}' unique_count_a_from_ac.txt''' % i)