Save amount of occurrences of a txt file to another python txt file

Asked

Viewed 140 times

1

This part of the code counts the number of times words repeat in the text:

with open('/Users/DIGITAL/Desktop/Python/teste.txt') as f:
    ocorrencias = Counter(f.read().split())

This part is used to sort in ascending order:

with open('/Users/DIGITAL/Desktop/Python/teste.txt') as f:

    palavras = Counter( f.read().split())
print ("Ordem por número de ocorrências:",ordenar(palavras, reverse=False))

I need to know a way to save the outcome of this {palavras = Counter( f.read().split())} in a new txt file

1 answer

2


Dictionaries do not have ordination in Python! The secret is to convert the dictionary to a list of tuples and then sort it:

from collections import Counter

# Abre arquivo de Entrada para leitura
with open('texto.txt', 'r') as f:

    # Calcula Quantidade de cada Palavra no Arquivo
    # e retorna um dicionario
    dic = Counter( f.read().split() )

# Converte Items do Dicionario Para Lista de Tuplas
lst = list(dic.items());

# Ordena Lista de Tuplas
lst.sort( key=lambda tup: tup[1])

# Abre arquivo de Saida para gravacao
with open('saida.txt','w') as f:

    # Para cada tupla na lista
    for tup in lst:

        # Grava linha no arquivo de Saida
        f.write( tup[0] + ":" + str(tup[1]) + "\n" )

text.txt

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam eget ligula eu
lectus lobortis condimentum.Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Etiam eget ligula eu lectus lobortis condimentum. Aliquam nonummy auctor
massa. Pellentesque habitant morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Nulla at risus. Quisque purus magna, auctor et, sagittis
ac, posuere eu, lectus. Nam mattis, felis ut adipiscing. Lorem ipsum dolor sit
amet, consectetur adipiscing elit. Etiam eget ligula eu lectus lobortis condimentum.

output.txt

habitant:1
Nulla:1
at:1
felis:1
morbi:1
Nam:1
lectus.:1
senectus:1
mattis,:1
posuere:1
purus:1
egestas.:1
tristique:1
Pellentesque:1
eu,:1
Quisque:1
condimentum.Lorem:1
et,:1
risus.:1
fames:1
massa.:1
nonummy:1
ac,:1
netus:1
adipiscing.:1
ut:1
ac:1
turpis:1
magna,:1
sagittis:1
Aliquam:1
malesuada:1
condimentum.:2
Lorem:2
auctor:2
et:2
amet,:3
ipsum:3
sit:3
lectus:3
ligula:3
consectetur:3
adipiscing:3
eget:3
dolor:3
eu:3
Etiam:3
lobortis:3
elit.:3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.