2014-01-17 63 views
1

我試圖從城市字典JSON API刪除\ r和\ n,但每次我使用應用re.sub我得到這個:刪除 r和 n的列表

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 
+0

郵政全回溯,好嗎? – inspectorG4dget

+3

你的意思是'/ r'和'/ n',它們是兩個字符的字符串還是'\ r'和'\ n',它們分別是回車和換行符的轉義序列? –

+0

[正則表達式用原來的替換「轉義」字符]的可能的重複(http://stackoverflow.com/questions/16866339/regular-expression-to-replace-escaped-characters-with-their-originals) – jonrsharpe

回答

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