Gabriel Machado
Gabriel Machado

Reputation: 29

Trying to count specific strings from a .txt file (python)

Actually I have an entry like this:

(observatório=astronómico, de o, universidade=de=coimbra)
(centro=de=astronomia, de o, universidade=do=porto=catarina=lobo)
(núcleo=interactivo=de=astronomia, em o,    centro=de=interpretação=ambiental=da=ponta=do=sal)
(câmara=municipal, de, cascais)
(câmara, de, nova=iorque)
(presidência, de o, pe)
(fortis, em, bruxelas)
(macquarie=futures, de o, eua)
(força=internacional=de=assistência=e=segurança, constituir o, força=de=reacção=rápida=do=comandante)
(forças=nacionais=destacadas, em o, afeganistão)
(nato, em o, afeganistão)
(nato, em o, afeganistão)

and need to count how many times a string repeats and output this in order to another .txt. I did it using dict, but was frustrating to .strip special characters.

# -*- coding: utf-8 -*-
# !/usr/bin/python
from Tkinter import Tk
from tkFileDialog import askopenfilename

Tk().withdraw() 
filename = askopenfilename()
file = open(filename, "r+")
wordcount = {}
for word in file.read().split():
     if word not in wordcount:
    wordcount[word] = 1
       else:
    wordcount[word] += 1
for k, v in wordcount.iteritems():
   print k, "=", v, "vez(es)"

any tip on how I may count it properly, and output it in a way anyone can read and know how many times a string(can be a line, because of the entry format) occurred?

Upvotes: 1

Views: 1076

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

As your text file contain none word characters you need to extract the word,for this aim you can use regex , then you can use collections.Counter to get a dictionary contain the frequency of words :

>>> from collections import Counter
>>> words=re.findall('\w+',s)
>>> Counter(words)
Counter({'o': 14, 'de': 12, 'em': 5, 'afeganist': 3, 'for': 3, 'do': 3, 'a': 3, 'ncia': 2, 'universidade': 2, 'mara': 2, 'astronomia': 2, 'nato': 2, 'centro': 2, 'c': 2, 'cascais': 1, 'ponta': 1, 'coimbra': 1, 'sal': 1, 'pida': 1, 'observat': 1, 'rio': 1, 'as': 1, 'catarina': 1, 'seguran': 1, 'macquarie': 1, 'nacionais': 1, 'nova': 1, 'eua': 1, 'interpreta': 1, 'internacional': 1, 'constituir': 1, 'pe': 1, 'reac': 1, 'bruxelas': 1, 'lobo': 1, 'assist': 1, 'municipal': 1, 'comandante': 1, 'da': 1, 'mico': 1, 'ambiental': 1, 'astron': 1, 'iorque': 1, 'fortis': 1, 'porto': 1, 'e': 1, 'futures': 1, 'n': 1, 'r': 1, 'interactivo': 1, 'presid': 1, 'destacadas': 1, 'cleo': 1})

\w+ will match any combinations of word characters with length 1 or more!

And for count a specific word you can use list.count() method:

>>> words.count('coimbra')
1
>>> words.count('a')
3

Upvotes: 1

Related Questions