TypeError: object of type 'map' has no len() on woggle v 1.2What's the canonical way to check for type in Python?How to determine a Python variable's type?How to know if an object has an attribute in PythonWhat is the meaning of a single and a double underscore before an object name?What are the differences between type() and isinstance()?In Python, how do I determine if an object is iterable?Determine the type of an object?null object in Python?Python class inherits objectTypeError: 'module' object is not callable

How do solar inverter systems easily add AC power sources together?

What's the point of fighting monsters in Zelda BoTW?

How to prevent a hosting company from accessing a VM's encryption keys?

Can I take a boxed bicycle on a German train?

How to emphasise the insignificance of someone/thing – besides using "klein"

Pen test results for web application include a file from a forbidden directory that is not even used or referenced

Why is explainability not one of the criteria for publication?

What are the IPSE’s, the ASPE’s, the FRIPSE’s and the GRIPSE’s?

Does the Reduce option from the Enlarge/Reduce spell cause a critical hit to do 2d4 less damage?

Is this password scheme legit?

Commercial company wants me to list all prior "inventions", give up everything not listed

Why is getting a PhD considered "financially irresponsible" by some people?

Videos of surgery

Defending Castle from Zombies

How to pass 2>/dev/null as a variable?

Could the UK amend the European Withdrawal Act and revoke the Article 50 invocation?

Federal Pacific 200a main panel problem with oversized 100a 2pole breaker

What to do about my 1-month-old boy peeing through diapers?

Counting the triangles that can be formed from segments of given lengths

Why did the population of Bhutan drop by 70% between 2007 and 2008?

What stops you from using fixed income in developing countries?

Dotted background on a flowchart

Is it unusual for a math department not to have a mail/web server?

Is there any problem with a full installation on a USB drive?



TypeError: object of type 'map' has no len() on woggle v 1.2


What's the canonical way to check for type in Python?How to determine a Python variable's type?How to know if an object has an attribute in PythonWhat is the meaning of a single and a double underscore before an object name?What are the differences between type() and isinstance()?In Python, how do I determine if an object is iterable?Determine the type of an object?null object in Python?Python class inherits objectTypeError: 'module' object is not callable






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm trying to use the wolfralpha on Woggle AI chatbot. However, I don't understand what is happening.



I tried to search it up and edit the code, but it seems the dev of woggle has become inactive.



import re
import os, time
import sqlite3
from collections import Counter
from string import punctuation
from math import sqrt
import wolframalpha # Get from here: https://pypi.python.org/pypi/wolframalpha
import ssl
import string
import smtplib
import urllib.request, urllib.parse, urllib.error
import urllib.request, urllib.error, urllib.parse
import random
import json
from html.parser import HTMLParser
import sys
import time


#Html stripper-outer used to format some responses received when online
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)

def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()

# A really poor way of doing things I know but it was just to test out an idea and I haven't updated it all yet
# Incoming lists - Remember they need to be in lower case
name = ['what is your name?', 'what are you called', 'what are you called?', 'what is your name', 'whats your name', 'whats your name?', "what's your name", "what's your name?"]
helpme = ['help', 'help.']
game = ['play a game', 'play with me', 'play game', 'hangman', 'hang man']
made = ['who made you?', 'who wrote you?', 'who wrote you', 'who made you', 'who created you?', 'who created you', 'when were you made?', 'when were you made', 'when were you born?', 'when were you born', 'when is your birthday?', 'when is your birthday', 'when is it your birthday?', 'when is it your birthday']
jez = ['who is jez whitworth?', 'who is jez whitworth', 'who is jez?', 'who is jez', 'tell me about jez', 'tell me about jez whitworth', 'jez whitworth', 'jez whitworth?']
swear = ['*** Enter you choice of swear words to be used by the swear filter here *****']
note = ['take note.', 'take note']
noteread = ['read note.', 'read note']
greetwoggle = ['hello woggle.', 'hi woggle.', 'hello woggle', 'hi woggle', 'hi', 'hello']
thanks = ['thanks.', 'thanks', 'thank you.', 'thank you', 'thnaks', 'thnaks.', 'thank', 'thank.', 'thx']


# Outgoing lists - Remember they need to be in lower case
howdy = ['Hi.', 'Hello.', 'Hi there.', "Hello, it's nice to chat to you.", 'Howdy.', 'Greetings.']
thanksreply = ['No problem.', 'No worries.', "You're welcome.", 'My pleasure.']


# Wolfram Alpha credentials - needed for general knowledge questions when online
appid = 'AH4WJ6-R8Y9JTGKJ7' # <--- Insert your free Wolfram Alpha token here - https://developer.wolframalpha.com/portal/apisignup.html
client = wolframalpha.Client(appid)

# Connection details for the conversation database. If there is no file present or the location is referenced
# incorrectly then a new blank conversation file will be produced automatically in the location you set below.
connection = sqlite3.connect('D:/WogglAI-FuctionalScript-master/conversation.sqlite') # <--- Just reference the location of the conversation file here
cursor = connection.cursor()

try:
# Create the table containing the words
cursor.execute('''
CREATE TABLE words (
word TEXT UNIQUE
)
''')
# Create the table containing the sentences
cursor.execute('''
CREATE TABLE sentences (
sentence TEXT UNIQUE,
used INT NOT NULL DEFAULT 0
)''')
# Create association between weighted words and the next sentence
cursor.execute('''
CREATE TABLE associations (
word_id INT NOT NULL,
sentence_id INT NOT NULL,
weight REAL NOT NULL)
''')
except:
pass

def get_id(entityName, text):
"""Retrieve an entity's unique ID from the database, given its associated text.
If the row is not already present, it is inserted.
The entity can either be a sentence or a word."""
tableName = entityName + 's'
columnName = entityName
cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))
row = cursor.fetchone()
if row:
return row[0]
else:
cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))
return cursor.lastrowid

def get_words(text):
"""Retrieve the words present in a given string of text.
The return value is a list of tuples where the first member is a lowercase word,
and the second member the number of time it is present in the text."""
wordsRegexpString = '(?:w+|[' + re.escape(punctuation) + ']+)'
wordsRegexp = re.compile(wordsRegexpString)
wordsList = wordsRegexp.findall(text.lower())
return list(Counter(wordsList).items())




B = 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn Woggle V1.2n Online...'
print(B)
while True:
# ask for user input; if a blank line, then exit
H = input('> ').strip()
HLower = H.lower()

if H == '':
print ("> Thanks for chatting.")
time.sleep(1)
os.system("sudo shutdown -h now")
break
# Wolframalpha
question = H.lower() # Lowercase
firstword = question.partition(' ')[0] # Gets first word
if firstword in ['question', 'question:', 'question-']:
query = question.split(' ',1)[1] # Removes first word
res = client.query(query)
if len(res.pods) > 0:
texts = ""
pod = res.pods[1]
if pod.text:
texts = pod.text
else:
texts = "I don't have an answer for that I'm afraid."
texts = texts.encode('ascii', 'ignore')
ab = string.replace (texts, "Wolfram|Alpha", "Woggle")
print(ab)
else:
print ("> Hmmm, I'm really not sure. Let me Google that...")
base = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&'
query = urllib.parse.urlencode('q' : question)
response = urllib.request.urlopen(base + query).read()
data = json.loads(response)
bc = data['responseData']['results'][0]['content']
googleanswer = strip_tags(bc)
print(googleanswer)
# End Wolframalpha
elif HLower in swear:
print ("> No bad language please.")
elif HLower in note:
notename = input("> Enter file name: ")
notecontent = input("Contents > ")
f = open(notename +".txt","w")
f.write(notecontent)
f.close()
elif HLower in noteread:
notename = input("> Enter file name to read: ")
try:
f = open(notename +".txt","r")
print((f.readline()))
f.close()
except:
pass
print ("> Sorry, I can't find a file of that name.")
elif HLower in name:
print ("> My name is Woggle.")
elif HLower in made:
print ("> I was activated on 1st January 2016 by my creator Jez Whitworth.")
elif HLower in jez:
print ("> Jez is a nice chap.")
elif HLower in helpme:
print ("n> Help menu: nOffline:nn1. Hangman - Start a game of hangman with Woggle.n2. Take note - Create a note for Woggle to save.n3. Read note - Get Woggle to relay previously saved notes.nnOnline:nnQuestion (followed by question): Ask Woggle any question.n")
elif HLower in greetwoggle:
print(("> ") + (random.choice(howdy)))
elif HLower in thanks:
print(("> ") + (random.choice(thanksreply)))
elif HLower in game:
# Words to play in the game - Just keep adding as many as you would like.
hangmanlist = ['bakso','mobil','takoyaki','indomie','bakmi','bajai','jakarta','bandung','rumah','jawa','gajah','jerapah','kucing','ulat','motor','nasi goreng','tempe','kacamata','monas','kerak telor','shrimp tempura','Adult','Aeroplane','Air','Aircraft Carrier','Airforce','Airport','Album','Alphabet','Apple','Arm','Army','Baby','Baby','Backpack','Balloon','Banana','Bank','Barbecue','Bathroom','Bathtub','Bed','Bed','Bee','Bible','Bible','Bird','Bomb','Book','Boss','Bottle','Bowl','Box','Boy','Brain','Bridge','Butterfly','Button','Cappuccino','Car','Carpet','Carrot','Cave','Chair','Chief','Child','Chisel','Chocolates','Church','Church','Circle','Circus','Circus','Clock','Clown','Coffee','Comet','Compact Disc','Compass','Computer','Crystal','Cup','Cycle','Data Base','Desk','Diamond','Dress','Drill','Drink','Drum','Dung','Ears','Earth','Egg','Electricity','Elephant','Eraser','Explosive','Eyes','Family','Fan','Feather','Festival','Film','Finger','Fire','Floodlight','Flower','Foot','Fork','Freeway','Fruit','Fungus','Game','Garden','Gas','Gate','Gemstone','Girl','Gloves','God','Grapes','Guitar','Hammer','Hat','Hieroglyph']
hangman = random.choice(hangmanlist)
hangman = hangman.lower()
print ("> Time to play hangman!")
time.sleep(1)
print ("> Start guessing...")
time.sleep(0.5)
word = hangman
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print((char,))
else:
print(("_",))
failed += 1
if failed == 0:
print ("n> You won. Well done.")
break
print()
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print ("Wrongn")
print(("You have"), + turns, ('more guesses'))
if turns == 0:
print(("> You Lose. The answer was ") + hangman)
else:
# Thanks to Mathieu Rodic for the below SQLite code. I tried various approaches but I found this simple
# method online and it did the same job in far fewer lines of code.
words = get_words(B)
words_length = sum([n * len(word) for word, n in words])
sentence_id = get_id('sentence', H)
for word, n in words:
word_id = get_id('word', word)
weight = sqrt(n / float(words_length))
cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))
connection.commit()
# retrieve the most likely answer from the database
cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')
words = get_words(H)
words_length = sum([n * len(word) for word, n in words])
for word, n in words:
weight = sqrt(n / float(words_length))
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,))
# if matches were found, give the best one
cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')
row = cursor.fetchone()
cursor.execute('DROP TABLE results')
# otherwise, just randomly pick one of the least used sentences
if row is None:
cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')
row = cursor.fetchone()

# tell the database the sentence has been used once more, and prepare the sentence
B = row[1]
cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))
print(('> ' + B))


On line 160 below #wolframalpha. The original code and how it's supposed to work can be found here
and the GitHub code here.










share|improve this question
































    0















    I'm trying to use the wolfralpha on Woggle AI chatbot. However, I don't understand what is happening.



    I tried to search it up and edit the code, but it seems the dev of woggle has become inactive.



    import re
    import os, time
    import sqlite3
    from collections import Counter
    from string import punctuation
    from math import sqrt
    import wolframalpha # Get from here: https://pypi.python.org/pypi/wolframalpha
    import ssl
    import string
    import smtplib
    import urllib.request, urllib.parse, urllib.error
    import urllib.request, urllib.error, urllib.parse
    import random
    import json
    from html.parser import HTMLParser
    import sys
    import time


    #Html stripper-outer used to format some responses received when online
    class MLStripper(HTMLParser):
    def __init__(self):
    self.reset()
    self.fed = []
    def handle_data(self, d):
    self.fed.append(d)
    def get_data(self):
    return ''.join(self.fed)

    def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

    # A really poor way of doing things I know but it was just to test out an idea and I haven't updated it all yet
    # Incoming lists - Remember they need to be in lower case
    name = ['what is your name?', 'what are you called', 'what are you called?', 'what is your name', 'whats your name', 'whats your name?', "what's your name", "what's your name?"]
    helpme = ['help', 'help.']
    game = ['play a game', 'play with me', 'play game', 'hangman', 'hang man']
    made = ['who made you?', 'who wrote you?', 'who wrote you', 'who made you', 'who created you?', 'who created you', 'when were you made?', 'when were you made', 'when were you born?', 'when were you born', 'when is your birthday?', 'when is your birthday', 'when is it your birthday?', 'when is it your birthday']
    jez = ['who is jez whitworth?', 'who is jez whitworth', 'who is jez?', 'who is jez', 'tell me about jez', 'tell me about jez whitworth', 'jez whitworth', 'jez whitworth?']
    swear = ['*** Enter you choice of swear words to be used by the swear filter here *****']
    note = ['take note.', 'take note']
    noteread = ['read note.', 'read note']
    greetwoggle = ['hello woggle.', 'hi woggle.', 'hello woggle', 'hi woggle', 'hi', 'hello']
    thanks = ['thanks.', 'thanks', 'thank you.', 'thank you', 'thnaks', 'thnaks.', 'thank', 'thank.', 'thx']


    # Outgoing lists - Remember they need to be in lower case
    howdy = ['Hi.', 'Hello.', 'Hi there.', "Hello, it's nice to chat to you.", 'Howdy.', 'Greetings.']
    thanksreply = ['No problem.', 'No worries.', "You're welcome.", 'My pleasure.']


    # Wolfram Alpha credentials - needed for general knowledge questions when online
    appid = 'AH4WJ6-R8Y9JTGKJ7' # <--- Insert your free Wolfram Alpha token here - https://developer.wolframalpha.com/portal/apisignup.html
    client = wolframalpha.Client(appid)

    # Connection details for the conversation database. If there is no file present or the location is referenced
    # incorrectly then a new blank conversation file will be produced automatically in the location you set below.
    connection = sqlite3.connect('D:/WogglAI-FuctionalScript-master/conversation.sqlite') # <--- Just reference the location of the conversation file here
    cursor = connection.cursor()

    try:
    # Create the table containing the words
    cursor.execute('''
    CREATE TABLE words (
    word TEXT UNIQUE
    )
    ''')
    # Create the table containing the sentences
    cursor.execute('''
    CREATE TABLE sentences (
    sentence TEXT UNIQUE,
    used INT NOT NULL DEFAULT 0
    )''')
    # Create association between weighted words and the next sentence
    cursor.execute('''
    CREATE TABLE associations (
    word_id INT NOT NULL,
    sentence_id INT NOT NULL,
    weight REAL NOT NULL)
    ''')
    except:
    pass

    def get_id(entityName, text):
    """Retrieve an entity's unique ID from the database, given its associated text.
    If the row is not already present, it is inserted.
    The entity can either be a sentence or a word."""
    tableName = entityName + 's'
    columnName = entityName
    cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))
    row = cursor.fetchone()
    if row:
    return row[0]
    else:
    cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))
    return cursor.lastrowid

    def get_words(text):
    """Retrieve the words present in a given string of text.
    The return value is a list of tuples where the first member is a lowercase word,
    and the second member the number of time it is present in the text."""
    wordsRegexpString = '(?:w+|[' + re.escape(punctuation) + ']+)'
    wordsRegexp = re.compile(wordsRegexpString)
    wordsList = wordsRegexp.findall(text.lower())
    return list(Counter(wordsList).items())




    B = 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn Woggle V1.2n Online...'
    print(B)
    while True:
    # ask for user input; if a blank line, then exit
    H = input('> ').strip()
    HLower = H.lower()

    if H == '':
    print ("> Thanks for chatting.")
    time.sleep(1)
    os.system("sudo shutdown -h now")
    break
    # Wolframalpha
    question = H.lower() # Lowercase
    firstword = question.partition(' ')[0] # Gets first word
    if firstword in ['question', 'question:', 'question-']:
    query = question.split(' ',1)[1] # Removes first word
    res = client.query(query)
    if len(res.pods) > 0:
    texts = ""
    pod = res.pods[1]
    if pod.text:
    texts = pod.text
    else:
    texts = "I don't have an answer for that I'm afraid."
    texts = texts.encode('ascii', 'ignore')
    ab = string.replace (texts, "Wolfram|Alpha", "Woggle")
    print(ab)
    else:
    print ("> Hmmm, I'm really not sure. Let me Google that...")
    base = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&'
    query = urllib.parse.urlencode('q' : question)
    response = urllib.request.urlopen(base + query).read()
    data = json.loads(response)
    bc = data['responseData']['results'][0]['content']
    googleanswer = strip_tags(bc)
    print(googleanswer)
    # End Wolframalpha
    elif HLower in swear:
    print ("> No bad language please.")
    elif HLower in note:
    notename = input("> Enter file name: ")
    notecontent = input("Contents > ")
    f = open(notename +".txt","w")
    f.write(notecontent)
    f.close()
    elif HLower in noteread:
    notename = input("> Enter file name to read: ")
    try:
    f = open(notename +".txt","r")
    print((f.readline()))
    f.close()
    except:
    pass
    print ("> Sorry, I can't find a file of that name.")
    elif HLower in name:
    print ("> My name is Woggle.")
    elif HLower in made:
    print ("> I was activated on 1st January 2016 by my creator Jez Whitworth.")
    elif HLower in jez:
    print ("> Jez is a nice chap.")
    elif HLower in helpme:
    print ("n> Help menu: nOffline:nn1. Hangman - Start a game of hangman with Woggle.n2. Take note - Create a note for Woggle to save.n3. Read note - Get Woggle to relay previously saved notes.nnOnline:nnQuestion (followed by question): Ask Woggle any question.n")
    elif HLower in greetwoggle:
    print(("> ") + (random.choice(howdy)))
    elif HLower in thanks:
    print(("> ") + (random.choice(thanksreply)))
    elif HLower in game:
    # Words to play in the game - Just keep adding as many as you would like.
    hangmanlist = ['bakso','mobil','takoyaki','indomie','bakmi','bajai','jakarta','bandung','rumah','jawa','gajah','jerapah','kucing','ulat','motor','nasi goreng','tempe','kacamata','monas','kerak telor','shrimp tempura','Adult','Aeroplane','Air','Aircraft Carrier','Airforce','Airport','Album','Alphabet','Apple','Arm','Army','Baby','Baby','Backpack','Balloon','Banana','Bank','Barbecue','Bathroom','Bathtub','Bed','Bed','Bee','Bible','Bible','Bird','Bomb','Book','Boss','Bottle','Bowl','Box','Boy','Brain','Bridge','Butterfly','Button','Cappuccino','Car','Carpet','Carrot','Cave','Chair','Chief','Child','Chisel','Chocolates','Church','Church','Circle','Circus','Circus','Clock','Clown','Coffee','Comet','Compact Disc','Compass','Computer','Crystal','Cup','Cycle','Data Base','Desk','Diamond','Dress','Drill','Drink','Drum','Dung','Ears','Earth','Egg','Electricity','Elephant','Eraser','Explosive','Eyes','Family','Fan','Feather','Festival','Film','Finger','Fire','Floodlight','Flower','Foot','Fork','Freeway','Fruit','Fungus','Game','Garden','Gas','Gate','Gemstone','Girl','Gloves','God','Grapes','Guitar','Hammer','Hat','Hieroglyph']
    hangman = random.choice(hangmanlist)
    hangman = hangman.lower()
    print ("> Time to play hangman!")
    time.sleep(1)
    print ("> Start guessing...")
    time.sleep(0.5)
    word = hangman
    guesses = ''
    turns = 10
    while turns > 0:
    failed = 0
    for char in word:
    if char in guesses:
    print((char,))
    else:
    print(("_",))
    failed += 1
    if failed == 0:
    print ("n> You won. Well done.")
    break
    print()
    guess = input("Guess a character:")
    guesses += guess
    if guess not in word:
    turns -= 1
    print ("Wrongn")
    print(("You have"), + turns, ('more guesses'))
    if turns == 0:
    print(("> You Lose. The answer was ") + hangman)
    else:
    # Thanks to Mathieu Rodic for the below SQLite code. I tried various approaches but I found this simple
    # method online and it did the same job in far fewer lines of code.
    words = get_words(B)
    words_length = sum([n * len(word) for word, n in words])
    sentence_id = get_id('sentence', H)
    for word, n in words:
    word_id = get_id('word', word)
    weight = sqrt(n / float(words_length))
    cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))
    connection.commit()
    # retrieve the most likely answer from the database
    cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')
    words = get_words(H)
    words_length = sum([n * len(word) for word, n in words])
    for word, n in words:
    weight = sqrt(n / float(words_length))
    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,))
    # if matches were found, give the best one
    cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')
    row = cursor.fetchone()
    cursor.execute('DROP TABLE results')
    # otherwise, just randomly pick one of the least used sentences
    if row is None:
    cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')
    row = cursor.fetchone()

    # tell the database the sentence has been used once more, and prepare the sentence
    B = row[1]
    cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))
    print(('> ' + B))


    On line 160 below #wolframalpha. The original code and how it's supposed to work can be found here
    and the GitHub code here.










    share|improve this question




























      0












      0








      0








      I'm trying to use the wolfralpha on Woggle AI chatbot. However, I don't understand what is happening.



      I tried to search it up and edit the code, but it seems the dev of woggle has become inactive.



      import re
      import os, time
      import sqlite3
      from collections import Counter
      from string import punctuation
      from math import sqrt
      import wolframalpha # Get from here: https://pypi.python.org/pypi/wolframalpha
      import ssl
      import string
      import smtplib
      import urllib.request, urllib.parse, urllib.error
      import urllib.request, urllib.error, urllib.parse
      import random
      import json
      from html.parser import HTMLParser
      import sys
      import time


      #Html stripper-outer used to format some responses received when online
      class MLStripper(HTMLParser):
      def __init__(self):
      self.reset()
      self.fed = []
      def handle_data(self, d):
      self.fed.append(d)
      def get_data(self):
      return ''.join(self.fed)

      def strip_tags(html):
      s = MLStripper()
      s.feed(html)
      return s.get_data()

      # A really poor way of doing things I know but it was just to test out an idea and I haven't updated it all yet
      # Incoming lists - Remember they need to be in lower case
      name = ['what is your name?', 'what are you called', 'what are you called?', 'what is your name', 'whats your name', 'whats your name?', "what's your name", "what's your name?"]
      helpme = ['help', 'help.']
      game = ['play a game', 'play with me', 'play game', 'hangman', 'hang man']
      made = ['who made you?', 'who wrote you?', 'who wrote you', 'who made you', 'who created you?', 'who created you', 'when were you made?', 'when were you made', 'when were you born?', 'when were you born', 'when is your birthday?', 'when is your birthday', 'when is it your birthday?', 'when is it your birthday']
      jez = ['who is jez whitworth?', 'who is jez whitworth', 'who is jez?', 'who is jez', 'tell me about jez', 'tell me about jez whitworth', 'jez whitworth', 'jez whitworth?']
      swear = ['*** Enter you choice of swear words to be used by the swear filter here *****']
      note = ['take note.', 'take note']
      noteread = ['read note.', 'read note']
      greetwoggle = ['hello woggle.', 'hi woggle.', 'hello woggle', 'hi woggle', 'hi', 'hello']
      thanks = ['thanks.', 'thanks', 'thank you.', 'thank you', 'thnaks', 'thnaks.', 'thank', 'thank.', 'thx']


      # Outgoing lists - Remember they need to be in lower case
      howdy = ['Hi.', 'Hello.', 'Hi there.', "Hello, it's nice to chat to you.", 'Howdy.', 'Greetings.']
      thanksreply = ['No problem.', 'No worries.', "You're welcome.", 'My pleasure.']


      # Wolfram Alpha credentials - needed for general knowledge questions when online
      appid = 'AH4WJ6-R8Y9JTGKJ7' # <--- Insert your free Wolfram Alpha token here - https://developer.wolframalpha.com/portal/apisignup.html
      client = wolframalpha.Client(appid)

      # Connection details for the conversation database. If there is no file present or the location is referenced
      # incorrectly then a new blank conversation file will be produced automatically in the location you set below.
      connection = sqlite3.connect('D:/WogglAI-FuctionalScript-master/conversation.sqlite') # <--- Just reference the location of the conversation file here
      cursor = connection.cursor()

      try:
      # Create the table containing the words
      cursor.execute('''
      CREATE TABLE words (
      word TEXT UNIQUE
      )
      ''')
      # Create the table containing the sentences
      cursor.execute('''
      CREATE TABLE sentences (
      sentence TEXT UNIQUE,
      used INT NOT NULL DEFAULT 0
      )''')
      # Create association between weighted words and the next sentence
      cursor.execute('''
      CREATE TABLE associations (
      word_id INT NOT NULL,
      sentence_id INT NOT NULL,
      weight REAL NOT NULL)
      ''')
      except:
      pass

      def get_id(entityName, text):
      """Retrieve an entity's unique ID from the database, given its associated text.
      If the row is not already present, it is inserted.
      The entity can either be a sentence or a word."""
      tableName = entityName + 's'
      columnName = entityName
      cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))
      row = cursor.fetchone()
      if row:
      return row[0]
      else:
      cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))
      return cursor.lastrowid

      def get_words(text):
      """Retrieve the words present in a given string of text.
      The return value is a list of tuples where the first member is a lowercase word,
      and the second member the number of time it is present in the text."""
      wordsRegexpString = '(?:w+|[' + re.escape(punctuation) + ']+)'
      wordsRegexp = re.compile(wordsRegexpString)
      wordsList = wordsRegexp.findall(text.lower())
      return list(Counter(wordsList).items())




      B = 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn Woggle V1.2n Online...'
      print(B)
      while True:
      # ask for user input; if a blank line, then exit
      H = input('> ').strip()
      HLower = H.lower()

      if H == '':
      print ("> Thanks for chatting.")
      time.sleep(1)
      os.system("sudo shutdown -h now")
      break
      # Wolframalpha
      question = H.lower() # Lowercase
      firstword = question.partition(' ')[0] # Gets first word
      if firstword in ['question', 'question:', 'question-']:
      query = question.split(' ',1)[1] # Removes first word
      res = client.query(query)
      if len(res.pods) > 0:
      texts = ""
      pod = res.pods[1]
      if pod.text:
      texts = pod.text
      else:
      texts = "I don't have an answer for that I'm afraid."
      texts = texts.encode('ascii', 'ignore')
      ab = string.replace (texts, "Wolfram|Alpha", "Woggle")
      print(ab)
      else:
      print ("> Hmmm, I'm really not sure. Let me Google that...")
      base = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&'
      query = urllib.parse.urlencode('q' : question)
      response = urllib.request.urlopen(base + query).read()
      data = json.loads(response)
      bc = data['responseData']['results'][0]['content']
      googleanswer = strip_tags(bc)
      print(googleanswer)
      # End Wolframalpha
      elif HLower in swear:
      print ("> No bad language please.")
      elif HLower in note:
      notename = input("> Enter file name: ")
      notecontent = input("Contents > ")
      f = open(notename +".txt","w")
      f.write(notecontent)
      f.close()
      elif HLower in noteread:
      notename = input("> Enter file name to read: ")
      try:
      f = open(notename +".txt","r")
      print((f.readline()))
      f.close()
      except:
      pass
      print ("> Sorry, I can't find a file of that name.")
      elif HLower in name:
      print ("> My name is Woggle.")
      elif HLower in made:
      print ("> I was activated on 1st January 2016 by my creator Jez Whitworth.")
      elif HLower in jez:
      print ("> Jez is a nice chap.")
      elif HLower in helpme:
      print ("n> Help menu: nOffline:nn1. Hangman - Start a game of hangman with Woggle.n2. Take note - Create a note for Woggle to save.n3. Read note - Get Woggle to relay previously saved notes.nnOnline:nnQuestion (followed by question): Ask Woggle any question.n")
      elif HLower in greetwoggle:
      print(("> ") + (random.choice(howdy)))
      elif HLower in thanks:
      print(("> ") + (random.choice(thanksreply)))
      elif HLower in game:
      # Words to play in the game - Just keep adding as many as you would like.
      hangmanlist = ['bakso','mobil','takoyaki','indomie','bakmi','bajai','jakarta','bandung','rumah','jawa','gajah','jerapah','kucing','ulat','motor','nasi goreng','tempe','kacamata','monas','kerak telor','shrimp tempura','Adult','Aeroplane','Air','Aircraft Carrier','Airforce','Airport','Album','Alphabet','Apple','Arm','Army','Baby','Baby','Backpack','Balloon','Banana','Bank','Barbecue','Bathroom','Bathtub','Bed','Bed','Bee','Bible','Bible','Bird','Bomb','Book','Boss','Bottle','Bowl','Box','Boy','Brain','Bridge','Butterfly','Button','Cappuccino','Car','Carpet','Carrot','Cave','Chair','Chief','Child','Chisel','Chocolates','Church','Church','Circle','Circus','Circus','Clock','Clown','Coffee','Comet','Compact Disc','Compass','Computer','Crystal','Cup','Cycle','Data Base','Desk','Diamond','Dress','Drill','Drink','Drum','Dung','Ears','Earth','Egg','Electricity','Elephant','Eraser','Explosive','Eyes','Family','Fan','Feather','Festival','Film','Finger','Fire','Floodlight','Flower','Foot','Fork','Freeway','Fruit','Fungus','Game','Garden','Gas','Gate','Gemstone','Girl','Gloves','God','Grapes','Guitar','Hammer','Hat','Hieroglyph']
      hangman = random.choice(hangmanlist)
      hangman = hangman.lower()
      print ("> Time to play hangman!")
      time.sleep(1)
      print ("> Start guessing...")
      time.sleep(0.5)
      word = hangman
      guesses = ''
      turns = 10
      while turns > 0:
      failed = 0
      for char in word:
      if char in guesses:
      print((char,))
      else:
      print(("_",))
      failed += 1
      if failed == 0:
      print ("n> You won. Well done.")
      break
      print()
      guess = input("Guess a character:")
      guesses += guess
      if guess not in word:
      turns -= 1
      print ("Wrongn")
      print(("You have"), + turns, ('more guesses'))
      if turns == 0:
      print(("> You Lose. The answer was ") + hangman)
      else:
      # Thanks to Mathieu Rodic for the below SQLite code. I tried various approaches but I found this simple
      # method online and it did the same job in far fewer lines of code.
      words = get_words(B)
      words_length = sum([n * len(word) for word, n in words])
      sentence_id = get_id('sentence', H)
      for word, n in words:
      word_id = get_id('word', word)
      weight = sqrt(n / float(words_length))
      cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))
      connection.commit()
      # retrieve the most likely answer from the database
      cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')
      words = get_words(H)
      words_length = sum([n * len(word) for word, n in words])
      for word, n in words:
      weight = sqrt(n / float(words_length))
      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,))
      # if matches were found, give the best one
      cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')
      row = cursor.fetchone()
      cursor.execute('DROP TABLE results')
      # otherwise, just randomly pick one of the least used sentences
      if row is None:
      cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')
      row = cursor.fetchone()

      # tell the database the sentence has been used once more, and prepare the sentence
      B = row[1]
      cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))
      print(('> ' + B))


      On line 160 below #wolframalpha. The original code and how it's supposed to work can be found here
      and the GitHub code here.










      share|improve this question
















      I'm trying to use the wolfralpha on Woggle AI chatbot. However, I don't understand what is happening.



      I tried to search it up and edit the code, but it seems the dev of woggle has become inactive.



      import re
      import os, time
      import sqlite3
      from collections import Counter
      from string import punctuation
      from math import sqrt
      import wolframalpha # Get from here: https://pypi.python.org/pypi/wolframalpha
      import ssl
      import string
      import smtplib
      import urllib.request, urllib.parse, urllib.error
      import urllib.request, urllib.error, urllib.parse
      import random
      import json
      from html.parser import HTMLParser
      import sys
      import time


      #Html stripper-outer used to format some responses received when online
      class MLStripper(HTMLParser):
      def __init__(self):
      self.reset()
      self.fed = []
      def handle_data(self, d):
      self.fed.append(d)
      def get_data(self):
      return ''.join(self.fed)

      def strip_tags(html):
      s = MLStripper()
      s.feed(html)
      return s.get_data()

      # A really poor way of doing things I know but it was just to test out an idea and I haven't updated it all yet
      # Incoming lists - Remember they need to be in lower case
      name = ['what is your name?', 'what are you called', 'what are you called?', 'what is your name', 'whats your name', 'whats your name?', "what's your name", "what's your name?"]
      helpme = ['help', 'help.']
      game = ['play a game', 'play with me', 'play game', 'hangman', 'hang man']
      made = ['who made you?', 'who wrote you?', 'who wrote you', 'who made you', 'who created you?', 'who created you', 'when were you made?', 'when were you made', 'when were you born?', 'when were you born', 'when is your birthday?', 'when is your birthday', 'when is it your birthday?', 'when is it your birthday']
      jez = ['who is jez whitworth?', 'who is jez whitworth', 'who is jez?', 'who is jez', 'tell me about jez', 'tell me about jez whitworth', 'jez whitworth', 'jez whitworth?']
      swear = ['*** Enter you choice of swear words to be used by the swear filter here *****']
      note = ['take note.', 'take note']
      noteread = ['read note.', 'read note']
      greetwoggle = ['hello woggle.', 'hi woggle.', 'hello woggle', 'hi woggle', 'hi', 'hello']
      thanks = ['thanks.', 'thanks', 'thank you.', 'thank you', 'thnaks', 'thnaks.', 'thank', 'thank.', 'thx']


      # Outgoing lists - Remember they need to be in lower case
      howdy = ['Hi.', 'Hello.', 'Hi there.', "Hello, it's nice to chat to you.", 'Howdy.', 'Greetings.']
      thanksreply = ['No problem.', 'No worries.', "You're welcome.", 'My pleasure.']


      # Wolfram Alpha credentials - needed for general knowledge questions when online
      appid = 'AH4WJ6-R8Y9JTGKJ7' # <--- Insert your free Wolfram Alpha token here - https://developer.wolframalpha.com/portal/apisignup.html
      client = wolframalpha.Client(appid)

      # Connection details for the conversation database. If there is no file present or the location is referenced
      # incorrectly then a new blank conversation file will be produced automatically in the location you set below.
      connection = sqlite3.connect('D:/WogglAI-FuctionalScript-master/conversation.sqlite') # <--- Just reference the location of the conversation file here
      cursor = connection.cursor()

      try:
      # Create the table containing the words
      cursor.execute('''
      CREATE TABLE words (
      word TEXT UNIQUE
      )
      ''')
      # Create the table containing the sentences
      cursor.execute('''
      CREATE TABLE sentences (
      sentence TEXT UNIQUE,
      used INT NOT NULL DEFAULT 0
      )''')
      # Create association between weighted words and the next sentence
      cursor.execute('''
      CREATE TABLE associations (
      word_id INT NOT NULL,
      sentence_id INT NOT NULL,
      weight REAL NOT NULL)
      ''')
      except:
      pass

      def get_id(entityName, text):
      """Retrieve an entity's unique ID from the database, given its associated text.
      If the row is not already present, it is inserted.
      The entity can either be a sentence or a word."""
      tableName = entityName + 's'
      columnName = entityName
      cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))
      row = cursor.fetchone()
      if row:
      return row[0]
      else:
      cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))
      return cursor.lastrowid

      def get_words(text):
      """Retrieve the words present in a given string of text.
      The return value is a list of tuples where the first member is a lowercase word,
      and the second member the number of time it is present in the text."""
      wordsRegexpString = '(?:w+|[' + re.escape(punctuation) + ']+)'
      wordsRegexp = re.compile(wordsRegexpString)
      wordsList = wordsRegexp.findall(text.lower())
      return list(Counter(wordsList).items())




      B = 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn Woggle V1.2n Online...'
      print(B)
      while True:
      # ask for user input; if a blank line, then exit
      H = input('> ').strip()
      HLower = H.lower()

      if H == '':
      print ("> Thanks for chatting.")
      time.sleep(1)
      os.system("sudo shutdown -h now")
      break
      # Wolframalpha
      question = H.lower() # Lowercase
      firstword = question.partition(' ')[0] # Gets first word
      if firstword in ['question', 'question:', 'question-']:
      query = question.split(' ',1)[1] # Removes first word
      res = client.query(query)
      if len(res.pods) > 0:
      texts = ""
      pod = res.pods[1]
      if pod.text:
      texts = pod.text
      else:
      texts = "I don't have an answer for that I'm afraid."
      texts = texts.encode('ascii', 'ignore')
      ab = string.replace (texts, "Wolfram|Alpha", "Woggle")
      print(ab)
      else:
      print ("> Hmmm, I'm really not sure. Let me Google that...")
      base = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&'
      query = urllib.parse.urlencode('q' : question)
      response = urllib.request.urlopen(base + query).read()
      data = json.loads(response)
      bc = data['responseData']['results'][0]['content']
      googleanswer = strip_tags(bc)
      print(googleanswer)
      # End Wolframalpha
      elif HLower in swear:
      print ("> No bad language please.")
      elif HLower in note:
      notename = input("> Enter file name: ")
      notecontent = input("Contents > ")
      f = open(notename +".txt","w")
      f.write(notecontent)
      f.close()
      elif HLower in noteread:
      notename = input("> Enter file name to read: ")
      try:
      f = open(notename +".txt","r")
      print((f.readline()))
      f.close()
      except:
      pass
      print ("> Sorry, I can't find a file of that name.")
      elif HLower in name:
      print ("> My name is Woggle.")
      elif HLower in made:
      print ("> I was activated on 1st January 2016 by my creator Jez Whitworth.")
      elif HLower in jez:
      print ("> Jez is a nice chap.")
      elif HLower in helpme:
      print ("n> Help menu: nOffline:nn1. Hangman - Start a game of hangman with Woggle.n2. Take note - Create a note for Woggle to save.n3. Read note - Get Woggle to relay previously saved notes.nnOnline:nnQuestion (followed by question): Ask Woggle any question.n")
      elif HLower in greetwoggle:
      print(("> ") + (random.choice(howdy)))
      elif HLower in thanks:
      print(("> ") + (random.choice(thanksreply)))
      elif HLower in game:
      # Words to play in the game - Just keep adding as many as you would like.
      hangmanlist = ['bakso','mobil','takoyaki','indomie','bakmi','bajai','jakarta','bandung','rumah','jawa','gajah','jerapah','kucing','ulat','motor','nasi goreng','tempe','kacamata','monas','kerak telor','shrimp tempura','Adult','Aeroplane','Air','Aircraft Carrier','Airforce','Airport','Album','Alphabet','Apple','Arm','Army','Baby','Baby','Backpack','Balloon','Banana','Bank','Barbecue','Bathroom','Bathtub','Bed','Bed','Bee','Bible','Bible','Bird','Bomb','Book','Boss','Bottle','Bowl','Box','Boy','Brain','Bridge','Butterfly','Button','Cappuccino','Car','Carpet','Carrot','Cave','Chair','Chief','Child','Chisel','Chocolates','Church','Church','Circle','Circus','Circus','Clock','Clown','Coffee','Comet','Compact Disc','Compass','Computer','Crystal','Cup','Cycle','Data Base','Desk','Diamond','Dress','Drill','Drink','Drum','Dung','Ears','Earth','Egg','Electricity','Elephant','Eraser','Explosive','Eyes','Family','Fan','Feather','Festival','Film','Finger','Fire','Floodlight','Flower','Foot','Fork','Freeway','Fruit','Fungus','Game','Garden','Gas','Gate','Gemstone','Girl','Gloves','God','Grapes','Guitar','Hammer','Hat','Hieroglyph']
      hangman = random.choice(hangmanlist)
      hangman = hangman.lower()
      print ("> Time to play hangman!")
      time.sleep(1)
      print ("> Start guessing...")
      time.sleep(0.5)
      word = hangman
      guesses = ''
      turns = 10
      while turns > 0:
      failed = 0
      for char in word:
      if char in guesses:
      print((char,))
      else:
      print(("_",))
      failed += 1
      if failed == 0:
      print ("n> You won. Well done.")
      break
      print()
      guess = input("Guess a character:")
      guesses += guess
      if guess not in word:
      turns -= 1
      print ("Wrongn")
      print(("You have"), + turns, ('more guesses'))
      if turns == 0:
      print(("> You Lose. The answer was ") + hangman)
      else:
      # Thanks to Mathieu Rodic for the below SQLite code. I tried various approaches but I found this simple
      # method online and it did the same job in far fewer lines of code.
      words = get_words(B)
      words_length = sum([n * len(word) for word, n in words])
      sentence_id = get_id('sentence', H)
      for word, n in words:
      word_id = get_id('word', word)
      weight = sqrt(n / float(words_length))
      cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))
      connection.commit()
      # retrieve the most likely answer from the database
      cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')
      words = get_words(H)
      words_length = sum([n * len(word) for word, n in words])
      for word, n in words:
      weight = sqrt(n / float(words_length))
      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,))
      # if matches were found, give the best one
      cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')
      row = cursor.fetchone()
      cursor.execute('DROP TABLE results')
      # otherwise, just randomly pick one of the least used sentences
      if row is None:
      cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')
      row = cursor.fetchone()

      # tell the database the sentence has been used once more, and prepare the sentence
      B = row[1]
      cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))
      print(('> ' + B))


      On line 160 below #wolframalpha. The original code and how it's supposed to work can be found here
      and the GitHub code here.







      python python-3.7






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 20:20









      Pika the Wizard of the Whales

      2,1718 gold badges17 silver badges29 bronze badges




      2,1718 gold badges17 silver badges29 bronze badges










      asked Mar 27 at 16:36









      AikiAiki

      154 bronze badges




      154 bronze badges

























          2 Answers
          2






          active

          oldest

          votes


















          0















          As far as I can see, res.pods returns an object of type map, which is an iterator in Python 3+. I would assume this is your problem. To fix this, you can simply cast it as a list : len(list(res.pods)).



          Hope it helps






          share|improve this answer

























          • now brings up new problem such as typeerror: 'map' object is not subscribtable. on line 132 "pod=res.pods[1]"

            – Aiki
            Mar 28 at 0:51












          • This is because you execute res.pods again, which still returns a map object. To have access to list operations, such as '[ ]', you will need to cast it again as a list, or assign it to an object that you would then use instead of res.pods, like so : podsAsList = list(res.pods) and then use len(podsAsList) and pod = podsAsList[1].

            – Olivier Samson
            Mar 28 at 5:02











          • wut? im sorry im still new to python can you tell which line( e.g. line 139) to change

            – Aiki
            Mar 28 at 7:15











          • as far as I can see, you only need to change len(res.pods) and res.pods[1] to len(list(res.pods)) and list(res.pods)[[1] respectively.

            – Olivier Samson
            Mar 28 at 7:25











          • so after that there is a problem at line 138 or 139 "AttributeError: module 'string' has no attribute 'replace' ". I fixed the problem by deleting "string.replace", but if there is something wrong with my solution tell me. thanks for your help!

            – Aiki
            Mar 28 at 8:35


















          0















          just use this code



          import re
          import os, time
          import sqlite3
          from collections import Counter
          from string import punctuation
          from math import sqrt
          import wolframalpha # Get from here: https://pypi.python.org/pypi/wolframalpha
          import ssl
          import string
          import smtplib
          import urllib.request, urllib.parse, urllib.error
          import urllib.request, urllib.error, urllib.parse
          import random
          import json
          from html.parser import HTMLParser
          import sys
          import time


          #Html stripper-outer used to format some responses received when online
          class MLStripper(HTMLParser):
          def __init__(self):
          self.reset()
          self.fed = []
          def handle_data(self, d):
          self.fed.append(d)
          def get_data(self):
          return ''.join(self.fed)

          def strip_tags(html):
          s = MLStripper()
          s.feed(html)
          return s.get_data()

          # A really poor way of doing things I know but it was just to test out an idea and I haven't updated it all yet
          # Incoming lists - Remember they need to be in lower case
          name = ['what is your name?', 'what are you called', 'what are you called?', 'what is your name', 'whats your name', 'whats your name?', "what's your name", "what's your name?"]
          helpme = ['help', 'help.']
          game = ['play a game', 'play with me', 'play game', 'hangman', 'hang man']
          made = ['who made you?', 'who wrote you?', 'who wrote you', 'who made you', 'who created you?', 'who created you', 'when were you made?', 'when were you made', 'when were you born?', 'when were you born', 'when is your birthday?', 'when is your birthday', 'when is it your birthday?', 'when is it your birthday']
          jez = ['who is jez whitworth?', 'who is jez whitworth', 'who is jez?', 'who is jez', 'tell me about jez', 'tell me about jez whitworth', 'jez whitworth', 'jez whitworth?']
          swear = ['*** Enter you choice of swear words to be used by the swear filter here *****']
          note = ['take note.', 'take note']
          noteread = ['read note.', 'read note']
          greetwoggle = ['hello woggle.', 'hi woggle.', 'hello woggle', 'hi woggle']
          thanks = ['thanks.', 'thanks', 'thank you.', 'thank you', 'thnaks', 'thnaks.', 'thank', 'thank.']


          # Outgoing lists - Remember they need to be in lower case
          howdy = ['Hi.', 'Hello.', 'Hi there.', "Hello, it's nice to chat to you.", 'Howdy.', 'Greetings.']
          thanksreply = ['No problem.', 'No worries.', "You're welcome.", 'My pleasure.']


          # Wolfram Alpha credentials - needed for general knowledge questions when online
          appid = 'AH4WJ6-R8Y9JTGKJ7' # <--- Insert your free Wolfram Alpha token here - https://developer.wolframalpha.com/portal/apisignup.html
          client = wolframalpha.Client(appid)

          # Connection details for the conversation database. If there is no file present or the location is referenced
          # incorrectly then a new blank conversation file will be produced automatically in the locahetion you set below.
          connection = sqlite3.connect('E:/WogglAI-FuctionalScript-master/conversation.sqlite') # <--- Just reference the location of the conversation file here
          cursor = connection.cursor()

          try:
          # Create the table containing the words
          cursor.execute('''
          CREATE TABLE words (
          word TEXT UNIQUE
          )
          ''')
          # Create the table containing the sentences
          cursor.execute('''
          CREATE TABLE sentences (
          sentence TEXT UNIQUE,
          used INT NOT NULL DEFAULT 0
          )''')
          # Create association between weighted words and the next sentence
          cursor.execute('''
          CREATE TABLE associations (
          word_id INT NOT NULL,
          sentence_id INT NOT NULL,
          weight REAL NOT NULL)
          ''')
          except:
          pass

          def get_id(entityName, text):
          """Retrieve an entity's unique ID from the database, given its associated text.
          If the row is not already present, it is inserted.
          The entity can either be a sentence or a word."""
          tableName = entityName + 's'
          columnName = entityName
          cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))
          row = cursor.fetchone()
          if row:
          return row[0]
          else:
          cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))
          return cursor.lastrowid

          def get_words(text):
          """Retrieve the words present in a given string of text.
          The return value is a list of tuples where the first member is a lowercase word,
          and the second member the number of time it is present in the text."""
          wordsRegexpString = '(?:w+|[' + re.escape(punctuation) + ']+)'
          wordsRegexp = re.compile(wordsRegexpString)
          wordsList = wordsRegexp.findall(text.lower())
          return list(Counter(wordsList).items())




          B = 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn Woggle V1.2n Online...'
          print(B)
          while True:
          # ask for user input; if a blank line, then exit
          H = input('> ').strip()
          HLower = H.lower()

          if H == '':
          print ("> Thanks for chatting.")
          time.sleep(1)
          os.system("sudo shutdown -h now")
          break
          # Wolframalpha
          question = H.lower() # Lowercase
          firstword = question.partition(' ')[0] # Gets first word
          if firstword in ['question', 'question:', 'question-']:
          query = question.split(' ',1)[1] # Removes first word
          res = client.query(query)
          if len(list(res.pods)) > 0:
          texts = ""
          pod = list(res.pods)[1]
          if pod.text:
          texts = pod.text
          else:
          texts = "I don't have an answer for that I'm afraid."
          texts = texts.encode('ascii', 'ignore')
          ab = texts
          print(ab)
          else:
          print ("> Hmmm, I'm really not sure. Let me Google that...")
          base = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&'
          query = urllib.parse.urlencode('q' : question)
          response = urllib.request.urlopen(base + query).read()
          data = json.loads(response)
          bc = data['responseData']['results'][0]['content']
          googleanswer = strip_tags(bc)
          print(googleanswer)
          # End Wolframalpha
          elif HLower in swear:
          print ("> No bad language please.")
          elif HLower in note:
          notename = input("> Enter file name: ")
          notecontent = input("Contents > ")
          f = open(notename +".txt","w")
          f.write(notecontent)
          f.close()
          elif HLower in noteread:
          notename = input("> Enter file name to read: ")
          try:
          f = open(notename +".txt","r")
          print((f.readline()))
          f.close()
          except:
          pass
          print ("> Sorry, I can't find a file of that name.")
          elif HLower in name:
          print ("> My name is Woggle.")
          elif HLower in made:
          print ("> I was activated on 1st January 2016 by my creator Jez Whitworth.")
          elif HLower in jez:
          print ("> Jez is a nice chap.")
          elif HLower in helpme:
          print ("n> Help menu: nOffline:nn1. Hangman - Start a game of hangman with Woggle.n2. Take note - Create a note for Woggle to save.n3. Read note - Get Woggle to relay previously saved notes.nnOnline:nnQuestion (followed by question): Ask Woggle any question.n")
          elif HLower in greetwoggle:
          print(("> ") + (random.choice(howdy)))
          elif HLower in thanks:
          print(("> ") + (random.choice(thanksreply)))
          elif HLower in game:
          # Words to play in the game - Just keep adding as many as you would like.
          hangmanlist = ['Adult','Aeroplane','Air','Aircraft Carrier','Airforce','Airport','Album','Alphabet','Apple','Arm','Army','Baby','Baby','Backpack','Balloon','Banana','Bank','Barbecue','Bathroom','Bathtub','Bed','Bed','Bee','Bible','Bible','Bird','Bomb','Book','Boss','Bottle','Bowl','Box','Boy','Brain','Bridge','Butterfly','Button','Cappuccino','Car','Carpet','Carrot','Cave','Chair','Chief','Child','Chisel','Chocolates','Church','Church','Circle','Circus','Circus','Clock','Clown','Coffee','Comet','Compact Disc','Compass','Computer','Crystal','Cup','Cycle','Data Base','Desk','Diamond','Dress','Drill','Drink','Drum','Dung','Ears','Earth','Egg','Electricity','Elephant','Eraser','Explosive','Eyes','Family','Fan','Feather','Festival','Film','Finger','Fire','Floodlight','Flower','Foot','Fork','Freeway','Fruit','Fungus','Game','Garden','Gas','Gate','Gemstone','Girl','Gloves','God','Grapes','Guitar','Hammer','Hat','Hieroglyph']
          hangman = random.choice(hangmanlist)
          hangman = hangman.lower()
          print ("> Time to play hangman!")
          time.sleep(1)
          print ("> Start guessing...")
          time.sleep(0.5)
          word = hangman
          guesses = ''
          turns = 10
          while turns > 0:
          failed = 0
          for char in word:
          if char in guesses:
          print((char,))
          else:
          print(("_",))
          failed += 1
          if failed == 0:
          print ("n> You won. Well done.")
          break
          print()
          guess = input("Guess a character:")
          guesses += guess
          if guess not in word:
          turns -= 1
          print ("Wrongn")
          print(("You have"), + turns, ('more guesses'))
          if turns == 0:
          print(("> You Lose. The answer was ") + hangman)
          else:
          # Thanks to Mathieu Rodic for the below SQLite code. I tried various approaches but I found this simple
          # method online and it did the same job in far fewer lines of code.
          words = get_words(B)
          words_length = sum([n * len(word) for word, n in words])
          sentence_id = get_id('sentence', H)
          for word, n in words:
          word_id = get_id('word', word)
          weight = sqrt(n / float(words_length))
          cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))
          connection.commit()
          # retrieve the most likely answer from the database
          cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')
          words = get_words(H)
          words_length = sum([n * len(word) for word, n in words])
          for word, n in words:
          weight = sqrt(n / float(words_length))
          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,))
          # if matches were found, give the best one
          cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')
          row = cursor.fetchone()
          cursor.execute('DROP TABLE results')
          # otherwise, just randomly pick one of the least used sentences
          if row is None:
          cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')
          row = cursor.fetchone()

          # tell the database the sentence has been used once more, and prepare the sentence
          B = row[1]
          cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))
          print(('> ' + B))





          share|improve this answer



























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55382304%2ftypeerror-object-of-type-map-has-no-len-on-woggle-v-1-2%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0















            As far as I can see, res.pods returns an object of type map, which is an iterator in Python 3+. I would assume this is your problem. To fix this, you can simply cast it as a list : len(list(res.pods)).



            Hope it helps






            share|improve this answer

























            • now brings up new problem such as typeerror: 'map' object is not subscribtable. on line 132 "pod=res.pods[1]"

              – Aiki
              Mar 28 at 0:51












            • This is because you execute res.pods again, which still returns a map object. To have access to list operations, such as '[ ]', you will need to cast it again as a list, or assign it to an object that you would then use instead of res.pods, like so : podsAsList = list(res.pods) and then use len(podsAsList) and pod = podsAsList[1].

              – Olivier Samson
              Mar 28 at 5:02











            • wut? im sorry im still new to python can you tell which line( e.g. line 139) to change

              – Aiki
              Mar 28 at 7:15











            • as far as I can see, you only need to change len(res.pods) and res.pods[1] to len(list(res.pods)) and list(res.pods)[[1] respectively.

              – Olivier Samson
              Mar 28 at 7:25











            • so after that there is a problem at line 138 or 139 "AttributeError: module 'string' has no attribute 'replace' ". I fixed the problem by deleting "string.replace", but if there is something wrong with my solution tell me. thanks for your help!

              – Aiki
              Mar 28 at 8:35















            0















            As far as I can see, res.pods returns an object of type map, which is an iterator in Python 3+. I would assume this is your problem. To fix this, you can simply cast it as a list : len(list(res.pods)).



            Hope it helps






            share|improve this answer

























            • now brings up new problem such as typeerror: 'map' object is not subscribtable. on line 132 "pod=res.pods[1]"

              – Aiki
              Mar 28 at 0:51












            • This is because you execute res.pods again, which still returns a map object. To have access to list operations, such as '[ ]', you will need to cast it again as a list, or assign it to an object that you would then use instead of res.pods, like so : podsAsList = list(res.pods) and then use len(podsAsList) and pod = podsAsList[1].

              – Olivier Samson
              Mar 28 at 5:02











            • wut? im sorry im still new to python can you tell which line( e.g. line 139) to change

              – Aiki
              Mar 28 at 7:15











            • as far as I can see, you only need to change len(res.pods) and res.pods[1] to len(list(res.pods)) and list(res.pods)[[1] respectively.

              – Olivier Samson
              Mar 28 at 7:25











            • so after that there is a problem at line 138 or 139 "AttributeError: module 'string' has no attribute 'replace' ". I fixed the problem by deleting "string.replace", but if there is something wrong with my solution tell me. thanks for your help!

              – Aiki
              Mar 28 at 8:35













            0














            0










            0









            As far as I can see, res.pods returns an object of type map, which is an iterator in Python 3+. I would assume this is your problem. To fix this, you can simply cast it as a list : len(list(res.pods)).



            Hope it helps






            share|improve this answer













            As far as I can see, res.pods returns an object of type map, which is an iterator in Python 3+. I would assume this is your problem. To fix this, you can simply cast it as a list : len(list(res.pods)).



            Hope it helps







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 27 at 20:46









            Olivier SamsonOlivier Samson

            5112 silver badges11 bronze badges




            5112 silver badges11 bronze badges















            • now brings up new problem such as typeerror: 'map' object is not subscribtable. on line 132 "pod=res.pods[1]"

              – Aiki
              Mar 28 at 0:51












            • This is because you execute res.pods again, which still returns a map object. To have access to list operations, such as '[ ]', you will need to cast it again as a list, or assign it to an object that you would then use instead of res.pods, like so : podsAsList = list(res.pods) and then use len(podsAsList) and pod = podsAsList[1].

              – Olivier Samson
              Mar 28 at 5:02











            • wut? im sorry im still new to python can you tell which line( e.g. line 139) to change

              – Aiki
              Mar 28 at 7:15











            • as far as I can see, you only need to change len(res.pods) and res.pods[1] to len(list(res.pods)) and list(res.pods)[[1] respectively.

              – Olivier Samson
              Mar 28 at 7:25











            • so after that there is a problem at line 138 or 139 "AttributeError: module 'string' has no attribute 'replace' ". I fixed the problem by deleting "string.replace", but if there is something wrong with my solution tell me. thanks for your help!

              – Aiki
              Mar 28 at 8:35

















            • now brings up new problem such as typeerror: 'map' object is not subscribtable. on line 132 "pod=res.pods[1]"

              – Aiki
              Mar 28 at 0:51












            • This is because you execute res.pods again, which still returns a map object. To have access to list operations, such as '[ ]', you will need to cast it again as a list, or assign it to an object that you would then use instead of res.pods, like so : podsAsList = list(res.pods) and then use len(podsAsList) and pod = podsAsList[1].

              – Olivier Samson
              Mar 28 at 5:02











            • wut? im sorry im still new to python can you tell which line( e.g. line 139) to change

              – Aiki
              Mar 28 at 7:15











            • as far as I can see, you only need to change len(res.pods) and res.pods[1] to len(list(res.pods)) and list(res.pods)[[1] respectively.

              – Olivier Samson
              Mar 28 at 7:25











            • so after that there is a problem at line 138 or 139 "AttributeError: module 'string' has no attribute 'replace' ". I fixed the problem by deleting "string.replace", but if there is something wrong with my solution tell me. thanks for your help!

              – Aiki
              Mar 28 at 8:35
















            now brings up new problem such as typeerror: 'map' object is not subscribtable. on line 132 "pod=res.pods[1]"

            – Aiki
            Mar 28 at 0:51






            now brings up new problem such as typeerror: 'map' object is not subscribtable. on line 132 "pod=res.pods[1]"

            – Aiki
            Mar 28 at 0:51














            This is because you execute res.pods again, which still returns a map object. To have access to list operations, such as '[ ]', you will need to cast it again as a list, or assign it to an object that you would then use instead of res.pods, like so : podsAsList = list(res.pods) and then use len(podsAsList) and pod = podsAsList[1].

            – Olivier Samson
            Mar 28 at 5:02





            This is because you execute res.pods again, which still returns a map object. To have access to list operations, such as '[ ]', you will need to cast it again as a list, or assign it to an object that you would then use instead of res.pods, like so : podsAsList = list(res.pods) and then use len(podsAsList) and pod = podsAsList[1].

            – Olivier Samson
            Mar 28 at 5:02













            wut? im sorry im still new to python can you tell which line( e.g. line 139) to change

            – Aiki
            Mar 28 at 7:15





            wut? im sorry im still new to python can you tell which line( e.g. line 139) to change

            – Aiki
            Mar 28 at 7:15













            as far as I can see, you only need to change len(res.pods) and res.pods[1] to len(list(res.pods)) and list(res.pods)[[1] respectively.

            – Olivier Samson
            Mar 28 at 7:25





            as far as I can see, you only need to change len(res.pods) and res.pods[1] to len(list(res.pods)) and list(res.pods)[[1] respectively.

            – Olivier Samson
            Mar 28 at 7:25













            so after that there is a problem at line 138 or 139 "AttributeError: module 'string' has no attribute 'replace' ". I fixed the problem by deleting "string.replace", but if there is something wrong with my solution tell me. thanks for your help!

            – Aiki
            Mar 28 at 8:35





            so after that there is a problem at line 138 or 139 "AttributeError: module 'string' has no attribute 'replace' ". I fixed the problem by deleting "string.replace", but if there is something wrong with my solution tell me. thanks for your help!

            – Aiki
            Mar 28 at 8:35













            0















            just use this code



            import re
            import os, time
            import sqlite3
            from collections import Counter
            from string import punctuation
            from math import sqrt
            import wolframalpha # Get from here: https://pypi.python.org/pypi/wolframalpha
            import ssl
            import string
            import smtplib
            import urllib.request, urllib.parse, urllib.error
            import urllib.request, urllib.error, urllib.parse
            import random
            import json
            from html.parser import HTMLParser
            import sys
            import time


            #Html stripper-outer used to format some responses received when online
            class MLStripper(HTMLParser):
            def __init__(self):
            self.reset()
            self.fed = []
            def handle_data(self, d):
            self.fed.append(d)
            def get_data(self):
            return ''.join(self.fed)

            def strip_tags(html):
            s = MLStripper()
            s.feed(html)
            return s.get_data()

            # A really poor way of doing things I know but it was just to test out an idea and I haven't updated it all yet
            # Incoming lists - Remember they need to be in lower case
            name = ['what is your name?', 'what are you called', 'what are you called?', 'what is your name', 'whats your name', 'whats your name?', "what's your name", "what's your name?"]
            helpme = ['help', 'help.']
            game = ['play a game', 'play with me', 'play game', 'hangman', 'hang man']
            made = ['who made you?', 'who wrote you?', 'who wrote you', 'who made you', 'who created you?', 'who created you', 'when were you made?', 'when were you made', 'when were you born?', 'when were you born', 'when is your birthday?', 'when is your birthday', 'when is it your birthday?', 'when is it your birthday']
            jez = ['who is jez whitworth?', 'who is jez whitworth', 'who is jez?', 'who is jez', 'tell me about jez', 'tell me about jez whitworth', 'jez whitworth', 'jez whitworth?']
            swear = ['*** Enter you choice of swear words to be used by the swear filter here *****']
            note = ['take note.', 'take note']
            noteread = ['read note.', 'read note']
            greetwoggle = ['hello woggle.', 'hi woggle.', 'hello woggle', 'hi woggle']
            thanks = ['thanks.', 'thanks', 'thank you.', 'thank you', 'thnaks', 'thnaks.', 'thank', 'thank.']


            # Outgoing lists - Remember they need to be in lower case
            howdy = ['Hi.', 'Hello.', 'Hi there.', "Hello, it's nice to chat to you.", 'Howdy.', 'Greetings.']
            thanksreply = ['No problem.', 'No worries.', "You're welcome.", 'My pleasure.']


            # Wolfram Alpha credentials - needed for general knowledge questions when online
            appid = 'AH4WJ6-R8Y9JTGKJ7' # <--- Insert your free Wolfram Alpha token here - https://developer.wolframalpha.com/portal/apisignup.html
            client = wolframalpha.Client(appid)

            # Connection details for the conversation database. If there is no file present or the location is referenced
            # incorrectly then a new blank conversation file will be produced automatically in the locahetion you set below.
            connection = sqlite3.connect('E:/WogglAI-FuctionalScript-master/conversation.sqlite') # <--- Just reference the location of the conversation file here
            cursor = connection.cursor()

            try:
            # Create the table containing the words
            cursor.execute('''
            CREATE TABLE words (
            word TEXT UNIQUE
            )
            ''')
            # Create the table containing the sentences
            cursor.execute('''
            CREATE TABLE sentences (
            sentence TEXT UNIQUE,
            used INT NOT NULL DEFAULT 0
            )''')
            # Create association between weighted words and the next sentence
            cursor.execute('''
            CREATE TABLE associations (
            word_id INT NOT NULL,
            sentence_id INT NOT NULL,
            weight REAL NOT NULL)
            ''')
            except:
            pass

            def get_id(entityName, text):
            """Retrieve an entity's unique ID from the database, given its associated text.
            If the row is not already present, it is inserted.
            The entity can either be a sentence or a word."""
            tableName = entityName + 's'
            columnName = entityName
            cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))
            row = cursor.fetchone()
            if row:
            return row[0]
            else:
            cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))
            return cursor.lastrowid

            def get_words(text):
            """Retrieve the words present in a given string of text.
            The return value is a list of tuples where the first member is a lowercase word,
            and the second member the number of time it is present in the text."""
            wordsRegexpString = '(?:w+|[' + re.escape(punctuation) + ']+)'
            wordsRegexp = re.compile(wordsRegexpString)
            wordsList = wordsRegexp.findall(text.lower())
            return list(Counter(wordsList).items())




            B = 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn Woggle V1.2n Online...'
            print(B)
            while True:
            # ask for user input; if a blank line, then exit
            H = input('> ').strip()
            HLower = H.lower()

            if H == '':
            print ("> Thanks for chatting.")
            time.sleep(1)
            os.system("sudo shutdown -h now")
            break
            # Wolframalpha
            question = H.lower() # Lowercase
            firstword = question.partition(' ')[0] # Gets first word
            if firstword in ['question', 'question:', 'question-']:
            query = question.split(' ',1)[1] # Removes first word
            res = client.query(query)
            if len(list(res.pods)) > 0:
            texts = ""
            pod = list(res.pods)[1]
            if pod.text:
            texts = pod.text
            else:
            texts = "I don't have an answer for that I'm afraid."
            texts = texts.encode('ascii', 'ignore')
            ab = texts
            print(ab)
            else:
            print ("> Hmmm, I'm really not sure. Let me Google that...")
            base = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&'
            query = urllib.parse.urlencode('q' : question)
            response = urllib.request.urlopen(base + query).read()
            data = json.loads(response)
            bc = data['responseData']['results'][0]['content']
            googleanswer = strip_tags(bc)
            print(googleanswer)
            # End Wolframalpha
            elif HLower in swear:
            print ("> No bad language please.")
            elif HLower in note:
            notename = input("> Enter file name: ")
            notecontent = input("Contents > ")
            f = open(notename +".txt","w")
            f.write(notecontent)
            f.close()
            elif HLower in noteread:
            notename = input("> Enter file name to read: ")
            try:
            f = open(notename +".txt","r")
            print((f.readline()))
            f.close()
            except:
            pass
            print ("> Sorry, I can't find a file of that name.")
            elif HLower in name:
            print ("> My name is Woggle.")
            elif HLower in made:
            print ("> I was activated on 1st January 2016 by my creator Jez Whitworth.")
            elif HLower in jez:
            print ("> Jez is a nice chap.")
            elif HLower in helpme:
            print ("n> Help menu: nOffline:nn1. Hangman - Start a game of hangman with Woggle.n2. Take note - Create a note for Woggle to save.n3. Read note - Get Woggle to relay previously saved notes.nnOnline:nnQuestion (followed by question): Ask Woggle any question.n")
            elif HLower in greetwoggle:
            print(("> ") + (random.choice(howdy)))
            elif HLower in thanks:
            print(("> ") + (random.choice(thanksreply)))
            elif HLower in game:
            # Words to play in the game - Just keep adding as many as you would like.
            hangmanlist = ['Adult','Aeroplane','Air','Aircraft Carrier','Airforce','Airport','Album','Alphabet','Apple','Arm','Army','Baby','Baby','Backpack','Balloon','Banana','Bank','Barbecue','Bathroom','Bathtub','Bed','Bed','Bee','Bible','Bible','Bird','Bomb','Book','Boss','Bottle','Bowl','Box','Boy','Brain','Bridge','Butterfly','Button','Cappuccino','Car','Carpet','Carrot','Cave','Chair','Chief','Child','Chisel','Chocolates','Church','Church','Circle','Circus','Circus','Clock','Clown','Coffee','Comet','Compact Disc','Compass','Computer','Crystal','Cup','Cycle','Data Base','Desk','Diamond','Dress','Drill','Drink','Drum','Dung','Ears','Earth','Egg','Electricity','Elephant','Eraser','Explosive','Eyes','Family','Fan','Feather','Festival','Film','Finger','Fire','Floodlight','Flower','Foot','Fork','Freeway','Fruit','Fungus','Game','Garden','Gas','Gate','Gemstone','Girl','Gloves','God','Grapes','Guitar','Hammer','Hat','Hieroglyph']
            hangman = random.choice(hangmanlist)
            hangman = hangman.lower()
            print ("> Time to play hangman!")
            time.sleep(1)
            print ("> Start guessing...")
            time.sleep(0.5)
            word = hangman
            guesses = ''
            turns = 10
            while turns > 0:
            failed = 0
            for char in word:
            if char in guesses:
            print((char,))
            else:
            print(("_",))
            failed += 1
            if failed == 0:
            print ("n> You won. Well done.")
            break
            print()
            guess = input("Guess a character:")
            guesses += guess
            if guess not in word:
            turns -= 1
            print ("Wrongn")
            print(("You have"), + turns, ('more guesses'))
            if turns == 0:
            print(("> You Lose. The answer was ") + hangman)
            else:
            # Thanks to Mathieu Rodic for the below SQLite code. I tried various approaches but I found this simple
            # method online and it did the same job in far fewer lines of code.
            words = get_words(B)
            words_length = sum([n * len(word) for word, n in words])
            sentence_id = get_id('sentence', H)
            for word, n in words:
            word_id = get_id('word', word)
            weight = sqrt(n / float(words_length))
            cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))
            connection.commit()
            # retrieve the most likely answer from the database
            cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')
            words = get_words(H)
            words_length = sum([n * len(word) for word, n in words])
            for word, n in words:
            weight = sqrt(n / float(words_length))
            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,))
            # if matches were found, give the best one
            cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')
            row = cursor.fetchone()
            cursor.execute('DROP TABLE results')
            # otherwise, just randomly pick one of the least used sentences
            if row is None:
            cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')
            row = cursor.fetchone()

            # tell the database the sentence has been used once more, and prepare the sentence
            B = row[1]
            cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))
            print(('> ' + B))





            share|improve this answer





























              0















              just use this code



              import re
              import os, time
              import sqlite3
              from collections import Counter
              from string import punctuation
              from math import sqrt
              import wolframalpha # Get from here: https://pypi.python.org/pypi/wolframalpha
              import ssl
              import string
              import smtplib
              import urllib.request, urllib.parse, urllib.error
              import urllib.request, urllib.error, urllib.parse
              import random
              import json
              from html.parser import HTMLParser
              import sys
              import time


              #Html stripper-outer used to format some responses received when online
              class MLStripper(HTMLParser):
              def __init__(self):
              self.reset()
              self.fed = []
              def handle_data(self, d):
              self.fed.append(d)
              def get_data(self):
              return ''.join(self.fed)

              def strip_tags(html):
              s = MLStripper()
              s.feed(html)
              return s.get_data()

              # A really poor way of doing things I know but it was just to test out an idea and I haven't updated it all yet
              # Incoming lists - Remember they need to be in lower case
              name = ['what is your name?', 'what are you called', 'what are you called?', 'what is your name', 'whats your name', 'whats your name?', "what's your name", "what's your name?"]
              helpme = ['help', 'help.']
              game = ['play a game', 'play with me', 'play game', 'hangman', 'hang man']
              made = ['who made you?', 'who wrote you?', 'who wrote you', 'who made you', 'who created you?', 'who created you', 'when were you made?', 'when were you made', 'when were you born?', 'when were you born', 'when is your birthday?', 'when is your birthday', 'when is it your birthday?', 'when is it your birthday']
              jez = ['who is jez whitworth?', 'who is jez whitworth', 'who is jez?', 'who is jez', 'tell me about jez', 'tell me about jez whitworth', 'jez whitworth', 'jez whitworth?']
              swear = ['*** Enter you choice of swear words to be used by the swear filter here *****']
              note = ['take note.', 'take note']
              noteread = ['read note.', 'read note']
              greetwoggle = ['hello woggle.', 'hi woggle.', 'hello woggle', 'hi woggle']
              thanks = ['thanks.', 'thanks', 'thank you.', 'thank you', 'thnaks', 'thnaks.', 'thank', 'thank.']


              # Outgoing lists - Remember they need to be in lower case
              howdy = ['Hi.', 'Hello.', 'Hi there.', "Hello, it's nice to chat to you.", 'Howdy.', 'Greetings.']
              thanksreply = ['No problem.', 'No worries.', "You're welcome.", 'My pleasure.']


              # Wolfram Alpha credentials - needed for general knowledge questions when online
              appid = 'AH4WJ6-R8Y9JTGKJ7' # <--- Insert your free Wolfram Alpha token here - https://developer.wolframalpha.com/portal/apisignup.html
              client = wolframalpha.Client(appid)

              # Connection details for the conversation database. If there is no file present or the location is referenced
              # incorrectly then a new blank conversation file will be produced automatically in the locahetion you set below.
              connection = sqlite3.connect('E:/WogglAI-FuctionalScript-master/conversation.sqlite') # <--- Just reference the location of the conversation file here
              cursor = connection.cursor()

              try:
              # Create the table containing the words
              cursor.execute('''
              CREATE TABLE words (
              word TEXT UNIQUE
              )
              ''')
              # Create the table containing the sentences
              cursor.execute('''
              CREATE TABLE sentences (
              sentence TEXT UNIQUE,
              used INT NOT NULL DEFAULT 0
              )''')
              # Create association between weighted words and the next sentence
              cursor.execute('''
              CREATE TABLE associations (
              word_id INT NOT NULL,
              sentence_id INT NOT NULL,
              weight REAL NOT NULL)
              ''')
              except:
              pass

              def get_id(entityName, text):
              """Retrieve an entity's unique ID from the database, given its associated text.
              If the row is not already present, it is inserted.
              The entity can either be a sentence or a word."""
              tableName = entityName + 's'
              columnName = entityName
              cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))
              row = cursor.fetchone()
              if row:
              return row[0]
              else:
              cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))
              return cursor.lastrowid

              def get_words(text):
              """Retrieve the words present in a given string of text.
              The return value is a list of tuples where the first member is a lowercase word,
              and the second member the number of time it is present in the text."""
              wordsRegexpString = '(?:w+|[' + re.escape(punctuation) + ']+)'
              wordsRegexp = re.compile(wordsRegexpString)
              wordsList = wordsRegexp.findall(text.lower())
              return list(Counter(wordsList).items())




              B = 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn Woggle V1.2n Online...'
              print(B)
              while True:
              # ask for user input; if a blank line, then exit
              H = input('> ').strip()
              HLower = H.lower()

              if H == '':
              print ("> Thanks for chatting.")
              time.sleep(1)
              os.system("sudo shutdown -h now")
              break
              # Wolframalpha
              question = H.lower() # Lowercase
              firstword = question.partition(' ')[0] # Gets first word
              if firstword in ['question', 'question:', 'question-']:
              query = question.split(' ',1)[1] # Removes first word
              res = client.query(query)
              if len(list(res.pods)) > 0:
              texts = ""
              pod = list(res.pods)[1]
              if pod.text:
              texts = pod.text
              else:
              texts = "I don't have an answer for that I'm afraid."
              texts = texts.encode('ascii', 'ignore')
              ab = texts
              print(ab)
              else:
              print ("> Hmmm, I'm really not sure. Let me Google that...")
              base = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&'
              query = urllib.parse.urlencode('q' : question)
              response = urllib.request.urlopen(base + query).read()
              data = json.loads(response)
              bc = data['responseData']['results'][0]['content']
              googleanswer = strip_tags(bc)
              print(googleanswer)
              # End Wolframalpha
              elif HLower in swear:
              print ("> No bad language please.")
              elif HLower in note:
              notename = input("> Enter file name: ")
              notecontent = input("Contents > ")
              f = open(notename +".txt","w")
              f.write(notecontent)
              f.close()
              elif HLower in noteread:
              notename = input("> Enter file name to read: ")
              try:
              f = open(notename +".txt","r")
              print((f.readline()))
              f.close()
              except:
              pass
              print ("> Sorry, I can't find a file of that name.")
              elif HLower in name:
              print ("> My name is Woggle.")
              elif HLower in made:
              print ("> I was activated on 1st January 2016 by my creator Jez Whitworth.")
              elif HLower in jez:
              print ("> Jez is a nice chap.")
              elif HLower in helpme:
              print ("n> Help menu: nOffline:nn1. Hangman - Start a game of hangman with Woggle.n2. Take note - Create a note for Woggle to save.n3. Read note - Get Woggle to relay previously saved notes.nnOnline:nnQuestion (followed by question): Ask Woggle any question.n")
              elif HLower in greetwoggle:
              print(("> ") + (random.choice(howdy)))
              elif HLower in thanks:
              print(("> ") + (random.choice(thanksreply)))
              elif HLower in game:
              # Words to play in the game - Just keep adding as many as you would like.
              hangmanlist = ['Adult','Aeroplane','Air','Aircraft Carrier','Airforce','Airport','Album','Alphabet','Apple','Arm','Army','Baby','Baby','Backpack','Balloon','Banana','Bank','Barbecue','Bathroom','Bathtub','Bed','Bed','Bee','Bible','Bible','Bird','Bomb','Book','Boss','Bottle','Bowl','Box','Boy','Brain','Bridge','Butterfly','Button','Cappuccino','Car','Carpet','Carrot','Cave','Chair','Chief','Child','Chisel','Chocolates','Church','Church','Circle','Circus','Circus','Clock','Clown','Coffee','Comet','Compact Disc','Compass','Computer','Crystal','Cup','Cycle','Data Base','Desk','Diamond','Dress','Drill','Drink','Drum','Dung','Ears','Earth','Egg','Electricity','Elephant','Eraser','Explosive','Eyes','Family','Fan','Feather','Festival','Film','Finger','Fire','Floodlight','Flower','Foot','Fork','Freeway','Fruit','Fungus','Game','Garden','Gas','Gate','Gemstone','Girl','Gloves','God','Grapes','Guitar','Hammer','Hat','Hieroglyph']
              hangman = random.choice(hangmanlist)
              hangman = hangman.lower()
              print ("> Time to play hangman!")
              time.sleep(1)
              print ("> Start guessing...")
              time.sleep(0.5)
              word = hangman
              guesses = ''
              turns = 10
              while turns > 0:
              failed = 0
              for char in word:
              if char in guesses:
              print((char,))
              else:
              print(("_",))
              failed += 1
              if failed == 0:
              print ("n> You won. Well done.")
              break
              print()
              guess = input("Guess a character:")
              guesses += guess
              if guess not in word:
              turns -= 1
              print ("Wrongn")
              print(("You have"), + turns, ('more guesses'))
              if turns == 0:
              print(("> You Lose. The answer was ") + hangman)
              else:
              # Thanks to Mathieu Rodic for the below SQLite code. I tried various approaches but I found this simple
              # method online and it did the same job in far fewer lines of code.
              words = get_words(B)
              words_length = sum([n * len(word) for word, n in words])
              sentence_id = get_id('sentence', H)
              for word, n in words:
              word_id = get_id('word', word)
              weight = sqrt(n / float(words_length))
              cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))
              connection.commit()
              # retrieve the most likely answer from the database
              cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')
              words = get_words(H)
              words_length = sum([n * len(word) for word, n in words])
              for word, n in words:
              weight = sqrt(n / float(words_length))
              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,))
              # if matches were found, give the best one
              cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')
              row = cursor.fetchone()
              cursor.execute('DROP TABLE results')
              # otherwise, just randomly pick one of the least used sentences
              if row is None:
              cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')
              row = cursor.fetchone()

              # tell the database the sentence has been used once more, and prepare the sentence
              B = row[1]
              cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))
              print(('> ' + B))





              share|improve this answer



























                0














                0










                0









                just use this code



                import re
                import os, time
                import sqlite3
                from collections import Counter
                from string import punctuation
                from math import sqrt
                import wolframalpha # Get from here: https://pypi.python.org/pypi/wolframalpha
                import ssl
                import string
                import smtplib
                import urllib.request, urllib.parse, urllib.error
                import urllib.request, urllib.error, urllib.parse
                import random
                import json
                from html.parser import HTMLParser
                import sys
                import time


                #Html stripper-outer used to format some responses received when online
                class MLStripper(HTMLParser):
                def __init__(self):
                self.reset()
                self.fed = []
                def handle_data(self, d):
                self.fed.append(d)
                def get_data(self):
                return ''.join(self.fed)

                def strip_tags(html):
                s = MLStripper()
                s.feed(html)
                return s.get_data()

                # A really poor way of doing things I know but it was just to test out an idea and I haven't updated it all yet
                # Incoming lists - Remember they need to be in lower case
                name = ['what is your name?', 'what are you called', 'what are you called?', 'what is your name', 'whats your name', 'whats your name?', "what's your name", "what's your name?"]
                helpme = ['help', 'help.']
                game = ['play a game', 'play with me', 'play game', 'hangman', 'hang man']
                made = ['who made you?', 'who wrote you?', 'who wrote you', 'who made you', 'who created you?', 'who created you', 'when were you made?', 'when were you made', 'when were you born?', 'when were you born', 'when is your birthday?', 'when is your birthday', 'when is it your birthday?', 'when is it your birthday']
                jez = ['who is jez whitworth?', 'who is jez whitworth', 'who is jez?', 'who is jez', 'tell me about jez', 'tell me about jez whitworth', 'jez whitworth', 'jez whitworth?']
                swear = ['*** Enter you choice of swear words to be used by the swear filter here *****']
                note = ['take note.', 'take note']
                noteread = ['read note.', 'read note']
                greetwoggle = ['hello woggle.', 'hi woggle.', 'hello woggle', 'hi woggle']
                thanks = ['thanks.', 'thanks', 'thank you.', 'thank you', 'thnaks', 'thnaks.', 'thank', 'thank.']


                # Outgoing lists - Remember they need to be in lower case
                howdy = ['Hi.', 'Hello.', 'Hi there.', "Hello, it's nice to chat to you.", 'Howdy.', 'Greetings.']
                thanksreply = ['No problem.', 'No worries.', "You're welcome.", 'My pleasure.']


                # Wolfram Alpha credentials - needed for general knowledge questions when online
                appid = 'AH4WJ6-R8Y9JTGKJ7' # <--- Insert your free Wolfram Alpha token here - https://developer.wolframalpha.com/portal/apisignup.html
                client = wolframalpha.Client(appid)

                # Connection details for the conversation database. If there is no file present or the location is referenced
                # incorrectly then a new blank conversation file will be produced automatically in the locahetion you set below.
                connection = sqlite3.connect('E:/WogglAI-FuctionalScript-master/conversation.sqlite') # <--- Just reference the location of the conversation file here
                cursor = connection.cursor()

                try:
                # Create the table containing the words
                cursor.execute('''
                CREATE TABLE words (
                word TEXT UNIQUE
                )
                ''')
                # Create the table containing the sentences
                cursor.execute('''
                CREATE TABLE sentences (
                sentence TEXT UNIQUE,
                used INT NOT NULL DEFAULT 0
                )''')
                # Create association between weighted words and the next sentence
                cursor.execute('''
                CREATE TABLE associations (
                word_id INT NOT NULL,
                sentence_id INT NOT NULL,
                weight REAL NOT NULL)
                ''')
                except:
                pass

                def get_id(entityName, text):
                """Retrieve an entity's unique ID from the database, given its associated text.
                If the row is not already present, it is inserted.
                The entity can either be a sentence or a word."""
                tableName = entityName + 's'
                columnName = entityName
                cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))
                row = cursor.fetchone()
                if row:
                return row[0]
                else:
                cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))
                return cursor.lastrowid

                def get_words(text):
                """Retrieve the words present in a given string of text.
                The return value is a list of tuples where the first member is a lowercase word,
                and the second member the number of time it is present in the text."""
                wordsRegexpString = '(?:w+|[' + re.escape(punctuation) + ']+)'
                wordsRegexp = re.compile(wordsRegexpString)
                wordsList = wordsRegexp.findall(text.lower())
                return list(Counter(wordsList).items())




                B = 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn Woggle V1.2n Online...'
                print(B)
                while True:
                # ask for user input; if a blank line, then exit
                H = input('> ').strip()
                HLower = H.lower()

                if H == '':
                print ("> Thanks for chatting.")
                time.sleep(1)
                os.system("sudo shutdown -h now")
                break
                # Wolframalpha
                question = H.lower() # Lowercase
                firstword = question.partition(' ')[0] # Gets first word
                if firstword in ['question', 'question:', 'question-']:
                query = question.split(' ',1)[1] # Removes first word
                res = client.query(query)
                if len(list(res.pods)) > 0:
                texts = ""
                pod = list(res.pods)[1]
                if pod.text:
                texts = pod.text
                else:
                texts = "I don't have an answer for that I'm afraid."
                texts = texts.encode('ascii', 'ignore')
                ab = texts
                print(ab)
                else:
                print ("> Hmmm, I'm really not sure. Let me Google that...")
                base = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&'
                query = urllib.parse.urlencode('q' : question)
                response = urllib.request.urlopen(base + query).read()
                data = json.loads(response)
                bc = data['responseData']['results'][0]['content']
                googleanswer = strip_tags(bc)
                print(googleanswer)
                # End Wolframalpha
                elif HLower in swear:
                print ("> No bad language please.")
                elif HLower in note:
                notename = input("> Enter file name: ")
                notecontent = input("Contents > ")
                f = open(notename +".txt","w")
                f.write(notecontent)
                f.close()
                elif HLower in noteread:
                notename = input("> Enter file name to read: ")
                try:
                f = open(notename +".txt","r")
                print((f.readline()))
                f.close()
                except:
                pass
                print ("> Sorry, I can't find a file of that name.")
                elif HLower in name:
                print ("> My name is Woggle.")
                elif HLower in made:
                print ("> I was activated on 1st January 2016 by my creator Jez Whitworth.")
                elif HLower in jez:
                print ("> Jez is a nice chap.")
                elif HLower in helpme:
                print ("n> Help menu: nOffline:nn1. Hangman - Start a game of hangman with Woggle.n2. Take note - Create a note for Woggle to save.n3. Read note - Get Woggle to relay previously saved notes.nnOnline:nnQuestion (followed by question): Ask Woggle any question.n")
                elif HLower in greetwoggle:
                print(("> ") + (random.choice(howdy)))
                elif HLower in thanks:
                print(("> ") + (random.choice(thanksreply)))
                elif HLower in game:
                # Words to play in the game - Just keep adding as many as you would like.
                hangmanlist = ['Adult','Aeroplane','Air','Aircraft Carrier','Airforce','Airport','Album','Alphabet','Apple','Arm','Army','Baby','Baby','Backpack','Balloon','Banana','Bank','Barbecue','Bathroom','Bathtub','Bed','Bed','Bee','Bible','Bible','Bird','Bomb','Book','Boss','Bottle','Bowl','Box','Boy','Brain','Bridge','Butterfly','Button','Cappuccino','Car','Carpet','Carrot','Cave','Chair','Chief','Child','Chisel','Chocolates','Church','Church','Circle','Circus','Circus','Clock','Clown','Coffee','Comet','Compact Disc','Compass','Computer','Crystal','Cup','Cycle','Data Base','Desk','Diamond','Dress','Drill','Drink','Drum','Dung','Ears','Earth','Egg','Electricity','Elephant','Eraser','Explosive','Eyes','Family','Fan','Feather','Festival','Film','Finger','Fire','Floodlight','Flower','Foot','Fork','Freeway','Fruit','Fungus','Game','Garden','Gas','Gate','Gemstone','Girl','Gloves','God','Grapes','Guitar','Hammer','Hat','Hieroglyph']
                hangman = random.choice(hangmanlist)
                hangman = hangman.lower()
                print ("> Time to play hangman!")
                time.sleep(1)
                print ("> Start guessing...")
                time.sleep(0.5)
                word = hangman
                guesses = ''
                turns = 10
                while turns > 0:
                failed = 0
                for char in word:
                if char in guesses:
                print((char,))
                else:
                print(("_",))
                failed += 1
                if failed == 0:
                print ("n> You won. Well done.")
                break
                print()
                guess = input("Guess a character:")
                guesses += guess
                if guess not in word:
                turns -= 1
                print ("Wrongn")
                print(("You have"), + turns, ('more guesses'))
                if turns == 0:
                print(("> You Lose. The answer was ") + hangman)
                else:
                # Thanks to Mathieu Rodic for the below SQLite code. I tried various approaches but I found this simple
                # method online and it did the same job in far fewer lines of code.
                words = get_words(B)
                words_length = sum([n * len(word) for word, n in words])
                sentence_id = get_id('sentence', H)
                for word, n in words:
                word_id = get_id('word', word)
                weight = sqrt(n / float(words_length))
                cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))
                connection.commit()
                # retrieve the most likely answer from the database
                cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')
                words = get_words(H)
                words_length = sum([n * len(word) for word, n in words])
                for word, n in words:
                weight = sqrt(n / float(words_length))
                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,))
                # if matches were found, give the best one
                cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')
                row = cursor.fetchone()
                cursor.execute('DROP TABLE results')
                # otherwise, just randomly pick one of the least used sentences
                if row is None:
                cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')
                row = cursor.fetchone()

                # tell the database the sentence has been used once more, and prepare the sentence
                B = row[1]
                cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))
                print(('> ' + B))





                share|improve this answer













                just use this code



                import re
                import os, time
                import sqlite3
                from collections import Counter
                from string import punctuation
                from math import sqrt
                import wolframalpha # Get from here: https://pypi.python.org/pypi/wolframalpha
                import ssl
                import string
                import smtplib
                import urllib.request, urllib.parse, urllib.error
                import urllib.request, urllib.error, urllib.parse
                import random
                import json
                from html.parser import HTMLParser
                import sys
                import time


                #Html stripper-outer used to format some responses received when online
                class MLStripper(HTMLParser):
                def __init__(self):
                self.reset()
                self.fed = []
                def handle_data(self, d):
                self.fed.append(d)
                def get_data(self):
                return ''.join(self.fed)

                def strip_tags(html):
                s = MLStripper()
                s.feed(html)
                return s.get_data()

                # A really poor way of doing things I know but it was just to test out an idea and I haven't updated it all yet
                # Incoming lists - Remember they need to be in lower case
                name = ['what is your name?', 'what are you called', 'what are you called?', 'what is your name', 'whats your name', 'whats your name?', "what's your name", "what's your name?"]
                helpme = ['help', 'help.']
                game = ['play a game', 'play with me', 'play game', 'hangman', 'hang man']
                made = ['who made you?', 'who wrote you?', 'who wrote you', 'who made you', 'who created you?', 'who created you', 'when were you made?', 'when were you made', 'when were you born?', 'when were you born', 'when is your birthday?', 'when is your birthday', 'when is it your birthday?', 'when is it your birthday']
                jez = ['who is jez whitworth?', 'who is jez whitworth', 'who is jez?', 'who is jez', 'tell me about jez', 'tell me about jez whitworth', 'jez whitworth', 'jez whitworth?']
                swear = ['*** Enter you choice of swear words to be used by the swear filter here *****']
                note = ['take note.', 'take note']
                noteread = ['read note.', 'read note']
                greetwoggle = ['hello woggle.', 'hi woggle.', 'hello woggle', 'hi woggle']
                thanks = ['thanks.', 'thanks', 'thank you.', 'thank you', 'thnaks', 'thnaks.', 'thank', 'thank.']


                # Outgoing lists - Remember they need to be in lower case
                howdy = ['Hi.', 'Hello.', 'Hi there.', "Hello, it's nice to chat to you.", 'Howdy.', 'Greetings.']
                thanksreply = ['No problem.', 'No worries.', "You're welcome.", 'My pleasure.']


                # Wolfram Alpha credentials - needed for general knowledge questions when online
                appid = 'AH4WJ6-R8Y9JTGKJ7' # <--- Insert your free Wolfram Alpha token here - https://developer.wolframalpha.com/portal/apisignup.html
                client = wolframalpha.Client(appid)

                # Connection details for the conversation database. If there is no file present or the location is referenced
                # incorrectly then a new blank conversation file will be produced automatically in the locahetion you set below.
                connection = sqlite3.connect('E:/WogglAI-FuctionalScript-master/conversation.sqlite') # <--- Just reference the location of the conversation file here
                cursor = connection.cursor()

                try:
                # Create the table containing the words
                cursor.execute('''
                CREATE TABLE words (
                word TEXT UNIQUE
                )
                ''')
                # Create the table containing the sentences
                cursor.execute('''
                CREATE TABLE sentences (
                sentence TEXT UNIQUE,
                used INT NOT NULL DEFAULT 0
                )''')
                # Create association between weighted words and the next sentence
                cursor.execute('''
                CREATE TABLE associations (
                word_id INT NOT NULL,
                sentence_id INT NOT NULL,
                weight REAL NOT NULL)
                ''')
                except:
                pass

                def get_id(entityName, text):
                """Retrieve an entity's unique ID from the database, given its associated text.
                If the row is not already present, it is inserted.
                The entity can either be a sentence or a word."""
                tableName = entityName + 's'
                columnName = entityName
                cursor.execute('SELECT rowid FROM ' + tableName + ' WHERE ' + columnName + ' = ?', (text,))
                row = cursor.fetchone()
                if row:
                return row[0]
                else:
                cursor.execute('INSERT INTO ' + tableName + ' (' + columnName + ') VALUES (?)', (text,))
                return cursor.lastrowid

                def get_words(text):
                """Retrieve the words present in a given string of text.
                The return value is a list of tuples where the first member is a lowercase word,
                and the second member the number of time it is present in the text."""
                wordsRegexpString = '(?:w+|[' + re.escape(punctuation) + ']+)'
                wordsRegexp = re.compile(wordsRegexpString)
                wordsList = wordsRegexp.findall(text.lower())
                return list(Counter(wordsList).items())




                B = 'nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn Woggle V1.2n Online...'
                print(B)
                while True:
                # ask for user input; if a blank line, then exit
                H = input('> ').strip()
                HLower = H.lower()

                if H == '':
                print ("> Thanks for chatting.")
                time.sleep(1)
                os.system("sudo shutdown -h now")
                break
                # Wolframalpha
                question = H.lower() # Lowercase
                firstword = question.partition(' ')[0] # Gets first word
                if firstword in ['question', 'question:', 'question-']:
                query = question.split(' ',1)[1] # Removes first word
                res = client.query(query)
                if len(list(res.pods)) > 0:
                texts = ""
                pod = list(res.pods)[1]
                if pod.text:
                texts = pod.text
                else:
                texts = "I don't have an answer for that I'm afraid."
                texts = texts.encode('ascii', 'ignore')
                ab = texts
                print(ab)
                else:
                print ("> Hmmm, I'm really not sure. Let me Google that...")
                base = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&'
                query = urllib.parse.urlencode('q' : question)
                response = urllib.request.urlopen(base + query).read()
                data = json.loads(response)
                bc = data['responseData']['results'][0]['content']
                googleanswer = strip_tags(bc)
                print(googleanswer)
                # End Wolframalpha
                elif HLower in swear:
                print ("> No bad language please.")
                elif HLower in note:
                notename = input("> Enter file name: ")
                notecontent = input("Contents > ")
                f = open(notename +".txt","w")
                f.write(notecontent)
                f.close()
                elif HLower in noteread:
                notename = input("> Enter file name to read: ")
                try:
                f = open(notename +".txt","r")
                print((f.readline()))
                f.close()
                except:
                pass
                print ("> Sorry, I can't find a file of that name.")
                elif HLower in name:
                print ("> My name is Woggle.")
                elif HLower in made:
                print ("> I was activated on 1st January 2016 by my creator Jez Whitworth.")
                elif HLower in jez:
                print ("> Jez is a nice chap.")
                elif HLower in helpme:
                print ("n> Help menu: nOffline:nn1. Hangman - Start a game of hangman with Woggle.n2. Take note - Create a note for Woggle to save.n3. Read note - Get Woggle to relay previously saved notes.nnOnline:nnQuestion (followed by question): Ask Woggle any question.n")
                elif HLower in greetwoggle:
                print(("> ") + (random.choice(howdy)))
                elif HLower in thanks:
                print(("> ") + (random.choice(thanksreply)))
                elif HLower in game:
                # Words to play in the game - Just keep adding as many as you would like.
                hangmanlist = ['Adult','Aeroplane','Air','Aircraft Carrier','Airforce','Airport','Album','Alphabet','Apple','Arm','Army','Baby','Baby','Backpack','Balloon','Banana','Bank','Barbecue','Bathroom','Bathtub','Bed','Bed','Bee','Bible','Bible','Bird','Bomb','Book','Boss','Bottle','Bowl','Box','Boy','Brain','Bridge','Butterfly','Button','Cappuccino','Car','Carpet','Carrot','Cave','Chair','Chief','Child','Chisel','Chocolates','Church','Church','Circle','Circus','Circus','Clock','Clown','Coffee','Comet','Compact Disc','Compass','Computer','Crystal','Cup','Cycle','Data Base','Desk','Diamond','Dress','Drill','Drink','Drum','Dung','Ears','Earth','Egg','Electricity','Elephant','Eraser','Explosive','Eyes','Family','Fan','Feather','Festival','Film','Finger','Fire','Floodlight','Flower','Foot','Fork','Freeway','Fruit','Fungus','Game','Garden','Gas','Gate','Gemstone','Girl','Gloves','God','Grapes','Guitar','Hammer','Hat','Hieroglyph']
                hangman = random.choice(hangmanlist)
                hangman = hangman.lower()
                print ("> Time to play hangman!")
                time.sleep(1)
                print ("> Start guessing...")
                time.sleep(0.5)
                word = hangman
                guesses = ''
                turns = 10
                while turns > 0:
                failed = 0
                for char in word:
                if char in guesses:
                print((char,))
                else:
                print(("_",))
                failed += 1
                if failed == 0:
                print ("n> You won. Well done.")
                break
                print()
                guess = input("Guess a character:")
                guesses += guess
                if guess not in word:
                turns -= 1
                print ("Wrongn")
                print(("You have"), + turns, ('more guesses'))
                if turns == 0:
                print(("> You Lose. The answer was ") + hangman)
                else:
                # Thanks to Mathieu Rodic for the below SQLite code. I tried various approaches but I found this simple
                # method online and it did the same job in far fewer lines of code.
                words = get_words(B)
                words_length = sum([n * len(word) for word, n in words])
                sentence_id = get_id('sentence', H)
                for word, n in words:
                word_id = get_id('word', word)
                weight = sqrt(n / float(words_length))
                cursor.execute('INSERT INTO associations VALUES (?, ?, ?)', (word_id, sentence_id, weight))
                connection.commit()
                # retrieve the most likely answer from the database
                cursor.execute('CREATE TEMPORARY TABLE results(sentence_id INT, sentence TEXT, weight REAL)')
                words = get_words(H)
                words_length = sum([n * len(word) for word, n in words])
                for word, n in words:
                weight = sqrt(n / float(words_length))
                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,))
                # if matches were found, give the best one
                cursor.execute('SELECT sentence_id, sentence, SUM(weight) AS sum_weight FROM results GROUP BY sentence_id ORDER BY sum_weight DESC LIMIT 1')
                row = cursor.fetchone()
                cursor.execute('DROP TABLE results')
                # otherwise, just randomly pick one of the least used sentences
                if row is None:
                cursor.execute('SELECT rowid, sentence FROM sentences WHERE used = (SELECT MIN(used) FROM sentences) ORDER BY RANDOM() LIMIT 1')
                row = cursor.fetchone()

                # tell the database the sentence has been used once more, and prepare the sentence
                B = row[1]
                cursor.execute('UPDATE sentences SET used=used+1 WHERE rowid=?', (row[0],))
                print(('> ' + B))






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 28 at 9:14









                AikiAiki

                154 bronze badges




                154 bronze badges






























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55382304%2ftypeerror-object-of-type-map-has-no-len-on-woggle-v-1-2%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript