![](/img/trans.png)
[英]Extract numbers from specific lines of a text file starting with strings in Python
[英]Python to extract specific numbers from text file
我有一个文本文件,在文本文件中是二进制数字,如35F,1,0,1,0,0。 我希望Python找到一个特定的组合,但首先在前面有一个学位数。
我想要Python做的是跳过该示例35F中的度数F数,并且只搜索1,0,1,0,0的所有二进制组合。 所以输出看起来应该是这样的
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
有几种方法,这似乎是最简单的方法:
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:])
如果所有行看起来都像00F 0,0,0,0,0
,则可以使用str.split()并将该部分保留在第一个空格之后。
counts = collections.Counter(l.split()[1] for l in infile)
编辑:如果没有空格,你也可以使用split(),输入如下所示: 00F,0,0,0,0,0
counts = collections.Counter(l.split(',',1)[1] for l in infile)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.