2015-02-07 118 views
1

我有一个文本文件,并在文本文件内有二进制数字,如35F,1,0,1,0,0我想python找到一个特定的组合,但首先有一个度数在前面。我想要python做的是跳过这个例子35F中的F数,然后搜索1,0,1,0,0的所有二进制组合。所以输出应该看起来像这样Python从文本文件中提取特定数字

28F 1,0,1,0,0 
15F 1,0,1,0,0 
18F 1,0,1,0,0 
20F 1,0,1,0,0 
22F 1,0,1,0,0 

在这一刻我有这个代码。 唯一的问题,我不能搜索我自己的具体组合它只告诉我有多少重复。

import collections 


with open('pythonbigDATA.txt') as infile: 
    counts = collections.Counter(l.strip() for l in infile) 
for line, count in counts.most_common(): 
    print count 
+0

找[Python的CSV(HTTPS://docs.python。 org/2/library/csv.html) – 2015-02-07 07:49:03

+0

“F”永远是你想要分裂的地方吗?试试''28F 1,0,1,0,0'.partition('F')' – dawg 2015-02-07 08:42:04

回答

3

有几个方面来说,这似乎是最简单的:

import csv 

combination = '1,0,1,0,0'.split(',') 

with open('pythonbigDATA.txt') as infile: 
    for row in csv.reader(infile): 
     if row[1:] == combination: 
      print row[0], ','.join(row[1:]) 
+0

是的,这个工作完全谢谢你 – 2015-02-07 20:07:57

0

如果所有线条看起来像这样00F 0,0,0,0,0你可以使用str.split()和第一空间后保留的部分。

counts = collections.Counter(l.split()[1] for l in infile) 

编辑:您还可以使用分裂()如果没有空间,输入如下:00F,0,0,0,0,0

counts = collections.Counter(l.split(',',1)[1] for l in infile) 
+0

在输入后有逗号后的温度,例如:'35F,1,0, 1,0,0' – mhawke 2015-02-07 09:34:18

+0

谢谢。然后我必须编辑这个答案。 – 2015-02-07 09:43:47