从列表中删除\ r和\ n

时间:2014-01-17 22:59:37

标签: python

我正在尝试从城市字典json api中删除\ r和\ n,但每次我使用re.sub我都会这样:

expected string or buffer

我不知道为什么,但这是代码:

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())

这是追溯:

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 

1 个答案:

答案 0 :(得分:2)

问题是您尝试在re.sub而不是字符串上使用dict。此外,您的代码在某些地方似乎有点混乱。试试这个:

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'

结果:

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