user19965401
user19965401

Reputation:

counter characters from a text file in python

I have a text file in python. This text file is like this:

Aragon is an autonomous community in northeastern Spain. The capital of Aragon is Zaragoza, which is also the most populous city in the autonomous community. Covering an area of ​​47720 km2, the region's terrain ranges from permanent glaciers through verdant valleys, rich pastures and orchards to the arid steppe plains of the central lowlands. Aragon is home to many rivers, most notably the Ebro, Spain's largest river, which flows west to east throughout the region through the province of Zaragoza. It is also home to the highest mountains in the Pyrenees.

Now I would like to create a dict from collections to count how many times each character occur.

I gave the following code for read the text file

with open("data/aragon.txt",'r') as data_file:
    for line in data_file:
        data = line.lower().strip().split()
        print(data)

Now I would like to now if there is an easier way to count the occurence of each character or is this the only method

from collections import Counter
Counter(['A','r','a','g','o','n','i','s','a','n','a','u','t','o','n','o','m','o','u','s','c','o','m','m','u','n','i','t','y','i','n','n','o','r','t','h','e','a','s','t','e','r','n','S','p','a','i','n','.'])

I did that just for the first phrase. But I would like to know if there is an easier way.

Upvotes: 0

Views: 61

Answers (1)

Ahmed AEK
Ahmed AEK

Reputation: 17516

you are nearly there, the counter object has a dictionary-like interface, so, you can call update on it with the string to update its internal contents.

from collections import Counter

counter = Counter()
with open("data/aragon.txt",'r') as data_file:
    for line in data_file:
        data = line.lower().strip()  # no split is needed
        counter.update(data)
        print(data)
print(counter)

Upvotes: 2

Related Questions