0

在下面file.txt显示的每个 ID 中,我需要检查为一个 ID 找到货币的次数。我怎样才能做到这一点?

文件.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

你会喜欢defaultdict

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 回答