#!/usr/bin/env python

from Tkinter import *
from tkFileDialog import *
from tkMessageBox import *
from os import getcwd


class CAplicacion:

def EliminaRepeticiones(self,lista):
"""Elimina elementos repetidos de una lista"""

for x in lista:
for y in range(lista.count(x) - 1):
lista.remove(x)

return lista


def QuitaSignosPuntuacion(self,linea):
"""Elimina caracteres no alfanuméricos de una línea de texto"""
reemplazables = [',','.',':',';','-','_','#','"','<','>','(','[','{','}',']',')','=']
for x in reemplazables:
linea = linea.replace(x,' ')
return linea

def ObtenerPalabras(self,fich):
"""Dado un fichero devuelve la lista de palabras que incluye"""

lineas = fich.readlines()
palabras = []
for linea in lineas:

linea = self.QuitaSignosPuntuacion(linea)

for palabra in linea.split():
palabras.append(palabra)

palabras = self.EliminaRepeticiones(palabras)

return palabras


def AbrirFichero(self):
"""Abre fichero y muestra sus palabras"""

self.textoestado.set("Abriendo...")

self.path = askopenfilename(title="Abrir Fichero", initialdir=getcwd(),

filetypes=[("Ficheros de texto","*.txt"), ("Cualquiera","*.*")], parent=self.panel)


try:
fich = file(self.path, "r")

except:
showwarning("Cachis la mar","No se puede abrir (%s)" % self.path)
return


self.textoestado.set("Procesando...")

palabras = self.ObtenerPalabras(fich)

palabras.sort()

for x in palabras:
self.lista.insert(END,x)


self.barrascroll_lista.pack(side=RIGHT, fill=Y)
self.lista.pack()

self.textoestado.set("Hecho")

def actualiza(widget):

"""Cambia el texto de la etiqueta por lapalbra sobre la que se ha clickeado"""
i = self.lista.curselection()
try:
i=map(int,i)
except ValueError:
pass

if (i!=[]):
self.textoestado.set(self.lista.get(i[0]))

self.lista.bind("<Double-Button-1>",actualiza)



def __init__(self,padre):

self.path = ''
self.panel = Frame(padre, width=500, height=300)
self.panel.pack()
#lo hago visible

self.botonAbrir = Button (self.panel, text="Abrir", background="black",

foreground="yellow", command=self.AbrirFichero)
#Creo un botón en panel q al pulsarlo abra un cuadro de diálogo y nos devuelva la ruta del fichero seleccionado por el usuario


self.botonCerrar = Button (self.panel, text="Cerrar",background="black",foreground="yellow", command=self.panel.quit)
self.botonAbrir.pack(side=LEFT)
self.botonCerrar.pack(side=RIGHT)
self.barrascroll_lista = Scrollbar(self.panel)


self.lista = Listbox (self.panel, yscrollcommand =self.barrascroll_lista.set, selectmode=SINGLE)
self.barrascroll_lista.config (command=self.lista.yview)

self.textoestado = StringVar()

self.estado = Label(self.panel, fg="red", textvariable=self.textoestado).pack(side=TOP)
self.textoestado.set("Esperando acción del usuario")


root = Tk()
root.title('Índice de palabras')
app = CAplicacion(root)
root.mainloop()