Python Forum
How to add multiple lines response in chatterbot?
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to add multiple lines response in chatterbot?
#1
I am trying to build a simple chat bot using Pythons's chatterbot.
I am training this bot with the help of ListTrainer.
I have created a txt file containing questions-answers.
Problem I am facing with it is that if answers contains multiple lines, bot includes only first line in response.
Can you please help me to solve this issue?
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
bot = ChatBot('MyBot')
conv = open('chats.txt','r').readlines()
bot.set_trainer(ListTrainer)
bot.train(conv)
while True:
   request = input('You:')
   response = bot.get_response(request)

print('Bot:',response)
And sample of chat.txt file is as below-
What are some common warning signs of stress and/or depression in men?
1. General signs of stress: Fast heart rate, Muscle tension Increase in blood pressure, Tense stomach
2. Long-term signs of stress: Frequent cold or flu, Headaches Trouble, sleeping Skin problems
Reply
#2
(May-16-2018, 06:48 AM)PrateekG Wrote:
conv = open('chats.txt','r').readlines()
In that line you are splitting all the multiple lines answers in single line entries of your table.
You need to fix a convention for your chat.txt file so you can recognise multiple lines responses.
The easiest thing is to use some well known format (json, yaml, .ini files...) but if you want to create your own, here is an example of a code that will concatenate lines that start with a space to the previous line:
with open('chats.txt','rt') as fd:
    conv = []
    last = ''
    for line in fd:
        # Remove newline and whitespaces only from the end of the line
        line = line.rstrip()
        if line.startswith(' '):
            last += line
        else:
            if last:
                conv.append(last)
            last = line
# Add the final string... last will be '' ony if the file is empty
if last:
    conv.append(last)
As format is not great (using spaces to specify the indent... where I have seen that Rolleyes) and you need to clean up more (remove duplicate spaces, check that any question has answers...), but shows you some ideas about how to preprocess your input to the chatbot.
Reply
#3
The suggested code snippet is giving me below error-
AttributeError: 'list' object has no attribute 'apend'
Reply
#4
it's a typo - should be append as elsewhere in the code
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
thanks buran! I changed this and tried again but getting response of only first line.
I will try with json format and let you all know.

I think the ListTrainer of chatterbot will not work for files other than txt.
If anyone can try with my code given above and get succeeded let me know.
Reply
#6
Sorry for the typo of append, I just edited it.

(May-16-2018, 12:11 PM)PrateekG Wrote: I think the ListTrainer of chatterbot will not work for files other than txt.
If anyone can try with my code given above and get succeeded let me know.

For what I saw in the docs (never used chatterbot) ListTrainer just need a list of strings, does not care about how you store them.

Just to build your full code, it shall look something like:
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot

bot = ChatBot('MyBot')

# Prepare the trining data
with open('chats.txt','rt') as fd:
    conv = []
    last = ''
    for line in fd:
        # Remove newline and whitespaces only from the end of the line
        line = line.rstrip()
        if line.startswith(' '):
            last += line
        else:
            if last:
                conv.append(last)
            last = line
# Add the final string... last will be '' ony if the file is empty
if last:
    conv.append(last)

bot.set_trainer(ListTrainer)
bot.train(conv)

while True:
   request = input('You:')
   if not request:
       break

   response = bot.get_response(request)
   print('Bot:', response)

print("That's all Folks!!!")
I also corrected the last while loop, that was not reporting the result of each request, just the last one.
Reply
#7
Somehow it is still not working as expected.
Please try with this question-answer in chats.txt=

What are some common warning signs of stress and/or depression in men?
General signs of stress:
Fast heart rate
Muscle tension
Increase in blood pressure
Tense stomach
Long-term signs of stress:
Frequent cold or flu
Headaches
Trouble sleeping
Skin problems
Digestion problems
Poor concentration
Negative thoughts
Speech problems
Anxiety
Irritability
Feelings of helplessness
Poor eating
Being accident prone
Aggression.
Reply
#8
Well, as I said, the code I posted expects a format from the input file more or less like:
  • Each entry will start by a character different to white space
  • Any line that starts with white space will be concatenated to the previous one

So you need to format your input files following this rules (you can -and shall- improve them, your input, your rules... make them practical for you) but if I format your example:
Output:
What are some common warning signs of stress and/or depression in men? General signs of stress: Fast heart rate Muscle tension Increase in blood pressure Tense stomach Long-term signs of stress: Frequent cold or flu Headaches Trouble sleeping Skin problems Digestion problems Poor concentration Negative thoughts Speech problems Anxiety Irritability Feelings of helplessness Poor eating Being accident prone Aggression.
Notice the blanks indenting the text
The array conv will have only 3 lines.
Reply
#9
I tried with this change also but the result is same.
Have you tried to run same code? What result did you get?
Reply
#10
Removing the chatterbot part (just interested in the input parser):
with open('chats.txt','rt') as fd:
    conv = []
    last = ''
    for line in fd:
        # Remove newline and whitespaces only from the end of the line
        line = line.rstrip()
        if line.startswith(' '):
            last += line
        else:
            if last:
                conv.append(last)
            last = line
# Add the final string... last will be '' ony if the file is empty
if last:
    conv.append(last)

for k, line in enumerate(conv):
    print(f"{k}: {line}")
The result is:
Output:
0: What are some common warning signs of stress and/or depression in men? 1: General signs of stress: Fast heart rate Muscle tension Increase in blood pressure Tense stomach 2: Long-term signs of stress: Frequent cold or flu Headaches Trouble sleeping Skin problems Digestion problems Poor concentration Negative thoughts Speech problems Anxiety Irritability Feelings of helplessness Poor eating Being accident prone Aggression.
So as you can see, only 3 lines (some of them really long) If you see it better, the conv array is:
[
  'What are some common warning signs of stress and/or depression in men?',
  'General signs of stress:  Fast heart rate  Muscle tension  Increase in blood pressure  Tense stomach',
  'Long-term signs of stress:  Frequent cold or flu  Headaches  Trouble sleeping  Skin problems  Digestion problems  Poor concentration  Negative thoughts  Speech problems  Anxiety  Irritability  Feelings of helplessness  Poor eating  Being accident prone  Aggression.'
]
You might need to improve the punctuation and format (i.e. there are many double spaces in the strings)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Amazon AWS - how to install the library chatterbot wpaiva 9 3,763 Feb-01-2020, 08:18 AM
Last Post: brighteningeyes
  Scrape multiple lines with regex greetings 2 3,021 Jul-04-2018, 09:09 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020