我正在学习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)
谢谢你的帮助!你知道吗
好吧,你的代码是朝着正确的方向发展的,但是你有一些东西被弄糊涂了。你知道吗
您需要将脚本所做的工作分为两个逻辑步骤:第一步,聚合(计数)所有
clu
字段。第二,写入clu
计数大于1的每个字段。你试着同时做这些步骤。。嗯,没用。从技术上讲,你可以这样做,但你的语法是错误的。不断地在文件中搜索内容也是非常低效的。最好只做一两次。你知道吗所以,让我们分开步骤。首先,计算你的
clu
字段。collections
模块有一个可以使用的Counter
。你知道吗c
现在是一个Counter
,可以用来查找给定clu
的计数。你知道吗相关问题 更多 >
编程相关推荐