I want to count the number of times any number (there are more than one) appears.

Asked 1 years ago, Updated 1 years ago, 307 views

Please understand that there may be some difficulties for beginners.

100111.ABC0001 100111.ABC221000000000200200
100111.ABC0001 100111.ABC22500000000200200
100111.ABC0002 100111.ABC3258000000000200200

Suppose you have a text file like the one above (simplified)
I'd like to count the number of times the next string of the first . appears, ABC0001,ABC0002.
ABC0001 may appear on the right side of the original file, so it would be helpful if you specify the location.

For this file
ABC00012 ABC00021
Ideally, the result should be

python

2023-01-19 11:04

1 Answers

I didn't think about the detailed conditions or error handling, but I wrote it roughly

$cat a.py
import re
import print

pattern='[^\.]+\.([^\s]+)\s.*'
counts = {}

with open('a.txt') as f:
  for line inf:
    key=re.match(pattern, line).group(1)
    counts.setdefault(key,0)
    counts [key] += 1

print.pprint(counts)

If you use the input data as the file 'a.txt', the results will be as follows:

$python a.py
{'ABC0001:2,'ABC0002':1}


2023-01-19 11:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.