我有一个制表符分隔的文件,我需要从中提取第12列的所有内容(文档类别)。然而,第12列的内容是高度重复的,所以首先我需要得到一个列表,只返回类别的数量(通过删除重复)。然后我需要找到一种方法来得到每个类别的行数。我的尝试如下:
def remove_duplicates(l): # define function to remove duplicates
return list(set(l))
input = sys.argv[1] # command line arguments to open tab file
infile = open(input)
for lines in infile: # split content into lines
words = lines.split("\t") # split lines into words i.e. columns
dataB2.append(words[11]) # column 12 contains the desired repetitive categories
dataB2 = dataA.sort() # sort the categories
dataB2 = remove_duplicates(dataA) # attempting to remove duplicates but this just returns an infinite list of 0's in the print command
print(len(dataB2))
infile.close()
我不知道怎样才能得到每个类别的行数呢? 所以我的问题是:如何有效地消除重复?我如何得到每个类别的行数?你知道吗
你需要做的就是从一个文件中读取每一行,按标签将其拆分,为每一行抓取第12列并将其放入一个列表中。(如果您不关心重复行,只需生成
column_12 = set()
,并使用add(item)
而不是append(item)
)。然后您只需使用len()来获取集合的长度。或者如果你想要两者,你可以使用一个列表,然后把它改成一个集合。你知道吗编辑:数一数每一个类别(感谢汤姆·莫里斯提醒我,我实际上没有回答这个问题)。您迭代列12的集合,以便不超过一次计数,并使用
count()
方法中构建的列表。你知道吗我建议使用pythonCounter来实现这一点。计数器几乎完全满足您的要求,因此您的代码如下所示:
相关问题 更多 >
编程相关推荐