elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Únete al Grupo Steam elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  [PYTHON] ChatBot que aprende
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [PYTHON] ChatBot que aprende  (Leído 5,666 veces)
<Trocutor>

Desconectado Desconectado

Mensajes: 72


Ver Perfil
[PYTHON] ChatBot que aprende
« en: 3 Septiembre 2017, 14:36 pm »

Hola buenas!!

Estoy intentando hacer un chat bot en Python en el que tu le dices algo y te contesta "inteligentemente" (Se que eso es IA pero esque noo tengo ni idea de como programarla  :()

Por ejemplo:

Código
  1. Yo Hola
  2. Bot Hola
  3. Yo cuanto tiempo
  4. bot (respuesta)

y mantener una conversacion "fluida" todo lo posible, tengo una parte hecha pero...alguien sabria como hacerlo aunque sea unas pocas lineas y yo lo sigo?

Gracias!!


En línea

engel lex
Moderador Global
***
Desconectado Desconectado

Mensajes: 15.514



Ver Perfil
Re: [PYTHON] ChatBot que aprende
« Respuesta #1 en: 3 Septiembre 2017, 16:53 pm »

lo primero es aprender IA XD con codigo estatico no será inteligente


En línea

El problema con la sociedad actualmente radica en que todos creen que tienen el derecho de tener una opinión, y que esa opinión sea validada por todos, cuando lo correcto es que todos tengan derecho a una opinión, siempre y cuando esa opinión pueda ser ignorada, cuestionada, e incluso ser sujeta a burla, particularmente cuando no tiene sentido alguno.
<Trocutor>

Desconectado Desconectado

Mensajes: 72


Ver Perfil
Re: [PYTHON] ChatBot que aprende
« Respuesta #2 en: 3 Septiembre 2017, 20:59 pm »

Ya xD el rpoblema esque he estado mirando libros y.... todos malos xD

Y en ingles me desenvuelvo pero si no esta bien claro... :rolleyes:
En línea

<Trocutor>

Desconectado Desconectado

Mensajes: 72


Ver Perfil
Re: [PYTHON] ChatBot que aprende
« Respuesta #3 en: 4 Septiembre 2017, 16:50 pm »

He encontrado este codigo por hay, pero no da respuestas logicas y no aprende muy bien que digamos

Código
  1. import re
  2. import sqlite3
  3. from collections import Counter
  4. from string import punctuation
  5. from math import sqrt
  6.  
  7. # initialize the connection to the database
  8. connection = sqlite3.connect('chatbot.sqlite')
  9. cursor = connection.cursor()
  10.  
  11. # create the tables needed by the program
  12. create_table_request_list = [
  13.    'CREATE TABLE words(word TEXT UNIQUE)',
  14.    'CREATE TABLE sentences(sentence TEXT UNIQUE, used INT NOT NULL DEFAULT 0)',
  15.    'CREATE TABLE associations (word_id INT NOT NULL, sentence_id INT NOT NULL, weight REAL NOT NULL)',
  16. ]
  17. for create_table_request in create_table_request_list:
  18.    try:
  19.        cursor.execute(create_table_request)
  20.    except:
  21.        pass
  22.  
  23. def get_id(entityName, text):
  24.    """Retrieve an entity's unique ID from the database, given its associated text.
  25.    If the row is not already present, it is inserted.
  26.    The entity can either be a sentence or a word."""
  27.    tableName = entityName + 's'
  28.    columnName = entityName
  29.    cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))
  30.    row = cursor.fetchone()
  31.    if row:
  32.        return row[0]
  33.    else:
  34.        cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))
  35.        return cursor.lastrowid
  36.  
  37. def get_words(text):
  38.    """Retrieve the words present in a given string of text.
  39.    The return value is a list of tuples where the first member is a lowercase word,
  40.    and the second member the number of time it is present in the text."""
  41.    wordsRegexpString = '(?:\w+|[' + re.escape(punctuation) + ']+)'
  42.    wordsRegexp = re.compile(wordsRegexpString)
  43.    wordsList = wordsRegexp.findall(text.lower())
  44.    return Counter(wordsList).items()
  45.  
  46.  
  47. B = 'Hello!'
  48. while True:
  49.    # output bot's message
  50.    print('B: ' + B)
  51.    # ask for user input; if blank line, exit the loop
  52.    H = raw_input('H: ').strip()
  53.    if H == '':
  54.        break
  55.    # store the association between the bot's message words and the user's response
  56.    words = get_words(B)
  57.    words_length = sum([n * len(word) for word, n in words])
  58.    sentence_id = get_id('sentence', H)
  59.    for word, n in words:
  60.        word_id = get_id('word', word)
  61.        weight = sqrt(n / float(words_length))
  62.        cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))
  63.    connection.commit()
  64.    # retrieve the most likely answer from the database
  65.    cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')
  66.    words = get_words(H)
  67.    words_length = sum([n * len(word) for word, n in words])
  68.    for word, n in words:
  69.        weight = sqrt(n / float(words_length))
  70.        cursor.execute('INSERT INTO results SELECT associations.sentence_id, sentences.sentence, ?*associations.weight/(4+sentences.used) FROM words INNER JOIN associations ON associations.word_id=words.rowid INNER JOIN sentences ON sentences.rowid=associations.sentence_id WHERE words.word=?', (weight, word,))
  71.    # if matches were found, give the best one
  72.    cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')
  73.    row = cursor.fetchone()
  74.    cursor.execute('DROP TABLE results')
  75.    # otherwise, just randomly pick one of the least used sentences
  76.    if row is None:
  77.        cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')
  78.        row = cursor.fetchone()
  79.    # tell the database the sentence has been used once more, and prepare the sentence
  80.    B = row[1]
  81.    cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))


CREDITOS:https://rodic.fr/blog/python-chatbot-1/
En línea

overxfl0w13

Desconectado Desconectado

Mensajes: 163



Ver Perfil WWW
Re: [PYTHON] ChatBot que aprende
« Respuesta #4 en: 10 Septiembre 2017, 03:37 am »

Puedes intentar usar esto: https://goo.gl/JVMv2D

:)
En línea

[/url]
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
[python]VideoTraining Aprende A Programar En Python desde 0 « 1 2 3 »
Scripting
juh 22 17,306 Último mensaje 16 Octubre 2010, 13:12 pm
por Pere Navarro
Aprende Python!, Python Interactivo
Scripting
Fran2013 0 2,161 Último mensaje 13 Noviembre 2013, 22:43 pm
por Fran2013
[Aporte] Aprende a programar juegos Python
Scripting
Yidu 5 4,924 Último mensaje 5 Septiembre 2015, 15:00 pm
por DeMoNcRaZy
[PYTHON] ChatBot en python
Scripting
<Trocutor> 0 1,448 Último mensaje 15 Mayo 2018, 20:40 pm
por <Trocutor>
[PYTHON] ChatBot para Whatsapp. ¿api de whatsapp o uso de python?
Scripting
OssoH 0 1,740 Último mensaje 26 Octubre 2022, 11:18 am
por OssoH
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines