例如有一盘点机文件,格式如下:
条码1,数量
条码2
条码1
条码3,3
条码1
条码2,2
然后统计出条码1,2,3的对应数量,没有,号的默认数量为1
这个可以用python的元组和字典来表示:
def read(s):
file=open(s,'r')
s=file.readlines()
s.sort()
print s
dict1={}
for x in s:
k=x[0:-1]
print ' : ',k
#if k.find(',')>0:
d=k.split(',')
e=d[0]
#else:
# e=k
print e
if dict1.has_key(e):
dict1[e]+=1
else:
dict1.setdefault(e,1)
for key,value in dict1.items():
#print key, ':', value
print '%s , %s' % (key,value)
read('mystr1.txt')
对应的测试文件mystr1.txt
101,1
101,2
102
101,3
102,2
101
103
103,3
102,1
103,5
104
另附perl写法:
#d:\perl\bin\perl.exe
open MYFILE,"GetNum.txt" or die ("How did you get logged in? ($!)");
my(@words,%count,$word);
chomp(@words=<MYFILE>);
foreach $word(@words) {
my $word1=(split(/,/, $word))[0];
$count{$word1} +=1;
}
foreach $word (keys %count) {
print "$word was seen $count{$word} times.\n";
}
CLOSE MYFILE;