1

I'm trying to remove \r and \n from a urban dictionary json api but everytime I use re.sub I get this:

expected string or buffer

I'm not sure why though, but here's the code:

elif used_prefix and cmd == "udi" and len(args) > 0 and self.getAccess(user) >= 1:
   try:
     f = urllib.request.urlopen("http://api.urbandictionary.com/v0/define?term=%s" % args.lower().replace(' ', '+'))
     data = json.loads(f.readall().decode("utf-8"))
     data = re.sub(r'\s+', ' ', data).replace("\\","")
     if (len(data['list']) > 0):
       definition = data['list'][0][u'definition']
       example = data['list'][0][u'example']
       permalink = data['list'][0][u'permalink']
       room.message("Urban Dictionary search for %s: %s Example: %s Link: %s" % (args.title(), definition, example, permalink), True)
     else: room.message("Word not found.")
except:
   room.message((str(sys.exc_info()[1])))
   print(traceback.format_exc())

This is the traceback:

Traceback (most recent call last): File "C:\Users\dell\Desktop\b0t\TutorialBot.py", line 2186, in onMessage data = re.sub(r'\s+', ' ', data).replace("\\","") File "C:\lib\re.py", line 170, in sub return _compile(pattern, flags).sub(repl, string, count) TypeError: expected string or buffer 
user3103923
  • 107
  • 9

1 Answers1

2

The problem is that you are trying to use re.sub on a dict rather than a string. Further, your code seems to be a little messy in places. Try this instead:

import urllib2
import json
import re

def test(*args):
     f = urllib2.urlopen("http://api.urbandictionary.com/v0/define?term=%s" % '+'.join(args).lower())  # note urllib2.urlopen rather than urllib.request.urlopen
     data = json.loads(f.read().decode("utf-8"))  # note f.read() instead of f.readall()
     if len(data['list']) > 0:
        definition = data['list'][0][u'definition']
        example = data['list'][0][u'example']
        permalink = data['list'][0][u'permalink']
        return "Urban Dictionary search for %s: %s Example: %s Link: %s" % (str(args), definition, example, permalink)  # returns a string

print test('mouth', 'hugging').replace('\n\n', '\n')  # prints the string after replacing '\n\n' with '\n'

The result:

Urban Dictionary search for ('mouth', 'hugging'): When you put a beer bottle in your mouth, and keep your mouth wrapped around it all day. Example: Josh: "mhmgdfhwrmhhh (attempts to talk while drinking a beer)"
Ryan: "You know I can't hear you when you're mouth hugging."
Josh: "mmmffwrrggddsshh" Link: http://mouth-hugging.urbanup.com/7493517
Justin O Barber
  • 11,291
  • 2
  • 40
  • 45