File with domain list and count domain tld with python

Viewed 26

I have test.txt with this data

a.com
b.com
c.net
c.online
c.unknowntld
ccc.unknown

How i can count all .com .net .online .unknowntld .unknown in test.txt

So i want get like this :

.com : 2
.net : 1
.online : 1
.unknowntld : 1
.unknown : 1

Thanks !

1 Answers

You can use the collections.Counter and str splitting to count.

from collections import Counter

cnt = Counter()

with open("test.txt", "rt") as f:
    for line in f:
        tld = line.rsplit(".", maxsplit=1)[-1]
        cnt[tld] += 1

cnt  # Counter({'com': 2, 'net': 1, 'online': 1, 'unknowntld': 1, 'unknown': 1})

If you need the leading period, you can just prepend it in the counter key cnt[f".{tld}"].

Related