0

以下file.txtでは、表示されているIDごとに、IDの通貨が検出された回数を確認する必要があります。これどうやってするの?

file.txt

  ID101\tbill is $200
  ID101\tyour bill
  ID101\t $200 again
  ID101\t$100 is the generated amount
  ID101\t$50 is your amount
  ID101\t$74 is the amount
  ID102\tNo bill
  ID102\tbill is $75
  ID103\t$65 is your bill
  ID103\tno bill

コード

f=open("file.txt")
arr=[]
count = 0
for l in f:     
   col = 0
   for i in l.split("\t"):
      if col == 0:
         if i not in arr: //tocheck whether it is a new id or not
            arr.append(i)
         if col == 1:
            if "$" in i:
              count += 1
      col += 1

各IDのカウントを確認するにはどうすればよいですか?

4

2 に答える 2

0

あなたはdefaultdictsを気に入るはずです:

from collections import defaultdict
counts = defaultdict(int)
with open("file.txt") as f:
    for line in f:
        id, content = line.split("\\t")
        if "$" in content:
            counts[id] += 1

idこれにより、単一の行に$記号が含まれていない場合、 sが完全に省略されることに注意してください。

于 2013-01-18T06:43:02.933 に答える
0
file = open('file.txt')
ids = {}
for line in file:
    if line.find('$') > -1:
        line_array = line.split("\t")
        id = line_array[0]
        if not ids.has_key(id):
            ids[id] = 0
        ids[id] += 1

for k in ids:
    print k + ': ' + str(ids[k])
于 2013-01-18T06:51:51.467 に答える