2013-11-24 39 views
0

我在学习Python并创建了此程序,但它不起作用,我希望有人能找到错误!删除以独特编号开头的行

我有了条目像这样的文件:

0 Kurthia sibirica Planococcaceae 
1593 Lactobacillus hordei Lactobacillaceae 
1121 Lactobacillus coleohominis Lactobacillaceae 
614 Lactobacillus coryniformis Lactobacillaceae 
57 Lactobacillus kitasatonis Lactobacillaceae 
3909 Lactobacillus malefermentans Lactobacillaceae 

我的目标是消除所有以数字,只有在整个文件中出现一次(唯一号码)开头的行,并保存所有以数字开头的行出现两次或更多次到新文件。这是我的尝试。它尚不能工作(当我让print线工作,从整个文件一行重复3次,这就是它):

#!/usr/bin/env python 

infilename = 'v35.clusternum.species.txt' 
outfilename = 'v13clusters.no.singletons.txt' 

#remove extra letters and spaces 
x = 0 
with open(infilename, 'r') as infile, open(outfilename, 'w') as outfile: 
     for line in infile: 
       clu, gen, spec, fam = line.split() 
     for clu in line: 
       if clu.count > 1: 
         #print line 
         outfile.write(line) 
       else: 
        x += 1 
print("Number of Singletons:") 
print(x) 

感谢您的帮助!

回答

2

好的,你的代码有点朝着正确的方向发展,但你有一些事情令人困惑。

您需要将您的脚本正在做的事情分成两个逻辑步骤:一个聚合(计数)所有clu字段。二,写每个字段的计数大于1。你试图在同一时间一起完成这些步骤,以及..呃,它不起作用。你可以从技术上这样做,但是你的语法错了。不断搜索文件以查找内容也是非常低效的。最好只做一两次。

所以,让我们分开这些步骤。首先,计算你的clu字段。 collections模块有一个Counter,您可以使用。

from collections import Counter 
with open(infilename, 'r') as infile: 
    c = Counter(line.split()[0] for line in infile) 

c现在是一个Counter,你可以用它来查找特定clu的计数。

with open(infilename, 'r') as infile, open(outfilename, 'w') as outfile: 
     for line in infile: 
       clu, gen, spec, fam = line.split() 
       if c[clu] > 1: 
        outfile.write(line) 
+0

我想你的意思是'计数器(line.split()[0]为infile中的行)'? – DSM

+0

@DSM是的,编辑,我们说话。 – roippi

+0

@roippi非常感谢!我想知道你是否可以再提出一件事:计算被删除的“数字数量”。因此,如果我的问题中以'0'和'57'开始的行只出现一次,我的'数字总和'就是2.我尝试这样做并插入一个'else:print([clu]) '把它打印出去的数字。 – Jen

相关问题