Esse programa varre um texto e mostra quais foram as palavras mais frequentes em ordem (você escolhe quantas palavras ele retornar) e mostra o tempo que levou para varrer o texto.
Ele varrer um texto que estiver na mesma pasta com o nome texto.txt, caso ele não exista executa a função novo texto e cole o texto, ou troque manualmente no diretório.
#coding:utf-8
from time import time
def novo_texto():
texto = open('texto.txt','w')
texto_usuario = raw_input('Entre com o texto: ')
texto.write(texto_usuario)
texto.close()
def executar_texto():
texto = open('texto.txt','r')
palavras = texto.read().split()
texto.close()
dicionario ={}
tempo_inicial = time()
controle = len(palavras)
for i in range(controle-1,-1,-1):
try:
dicionario[palavras[i]] = palavras.count(palavras[i])
except IndexError:
break
tempo_final = time()
tempo_exe = tempo_inicial - tempo_final
maiores_palavras = []
aux_chave = ''
maior = 0
numero_palavras = input('Quantas maiores palavras ? ')
if numero_palavras > len(palavras):
numero_palavras = len(palavras)
for j in range(numero_palavras):
for i in dicionario.iterkeys():
if dicionario[i] > maior:
maior = dicionario[i]
aux_chave=(i)
try:
del dicionario[aux_chave]
except KeyError:
break
maiores_palavras.append(aux_chave)
maior = 0
print
print 'Tempo:',tempo_exe
return 'Palavras mais repetidas:',maiores_palavras
OBS: testei com um texto de 50pg. e funcionou perfeitamente.
Eu tento manter meu código limpo, e você ?
Ele varrer um texto que estiver na mesma pasta com o nome texto.txt, caso ele não exista executa a função novo texto e cole o texto, ou troque manualmente no diretório.
#coding:utf-8
from time import time
def novo_texto():
texto = open('texto.txt','w')
texto_usuario = raw_input('Entre com o texto: ')
texto.write(texto_usuario)
texto.close()
def executar_texto():
texto = open('texto.txt','r')
palavras = texto.read().split()
texto.close()
dicionario ={}
tempo_inicial = time()
controle = len(palavras)
for i in range(controle-1,-1,-1):
try:
dicionario[palavras[i]] = palavras.count(palavras[i])
except IndexError:
break
tempo_final = time()
tempo_exe = tempo_inicial - tempo_final
maiores_palavras = []
aux_chave = ''
maior = 0
numero_palavras = input('Quantas maiores palavras ? ')
if numero_palavras > len(palavras):
numero_palavras = len(palavras)
for j in range(numero_palavras):
for i in dicionario.iterkeys():
if dicionario[i] > maior:
maior = dicionario[i]
aux_chave=(i)
try:
del dicionario[aux_chave]
except KeyError:
break
maiores_palavras.append(aux_chave)
maior = 0
print 'Tempo:',tempo_exe
return 'Palavras mais repetidas:',maiores_palavras
OBS: testei com um texto de 50pg. e funcionou perfeitamente.
Eu tento manter meu código limpo, e você ?
Comment