2010-03-21 98 views
1

我正試圖以這種方式從Python中調用gawk(AWK的GNU實現)。從Python調用gawk

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

我的問題是,「我」不是被它代表的值所代替。值「我」表示是一個整數,而不是一個字符串。我該如何解決這個問題?

+1

不要使用'os.system':改爲使用子進程(請參閱http://docs.python.org/library/subprocess.html)! – ChristopheD 2010-03-21 00:49:18

回答

1

你的問題是在引用,在Python中,像"some test "" with quotes"不會給你一個報價。試試這個:

os.system('''gawk '{if ($2=="%s") print $0}' unique_count_a_from_ac.txt''' % i) 
+0

謝謝!解決:) – forextremejunk 2010-03-21 00:51:11

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

+1 AMEN!他們不再向學校展示過程創造的成本嗎?! – 2010-03-21 07:50:32