本文整理汇总了Python中willie.web.quote函数的典型用法代码示例。如果您正苦于以下问题:Python quote函数的具体用法?Python quote怎么用?Python quote使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了quote函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: lastfm
def lastfm(willie, trigger):
user = trigger.group(2)
apikey = str(willie.config.lastfm.apikey)
if not (user and user != ''):
if trigger.nick in willie.db.preferences:
user = willie.db.preferences.get(trigger.nick, 'lastfm_user')
if not user:
willie.reply("Invalid username given or no username set. Use .fmset to set a username.")
return
#username variable prepared for insertion into REST string
quoted_user = web.quote(user)
#json formatted output for recent track
recent_page = web.get("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&format=json" % (quoted_user, apikey))
recent_track = json.loads(recent_page)['recenttracks']['track'][0]
#artist and track name pulled from recent_track
quoted_artist = web.quote(recent_track['artist']['#text'])
quoted_track = web.quote(recent_track['name'])
#json formatted track info
trackinfo_page = web.get("http://ws.audioscrobbler.com/2.0/?method=track.getInfo&artist=%s&track=%s&username=%s&api_key=%s&format=json" % (quoted_artist, quoted_track, quoted_user, apikey))
#track playcount and loved stats
trackinfo = json.loads(trackinfo_page)['track']
try:
playcount = trackinfo['userplaycount']
except KeyError:
playcount = "unknown"
loved = int(trackinfo['userloved'])
try:
if loved > 0:
willie.say('\x035' + u'\u2665' +'\x03 %s - %s - (%s plays)' % (recent_track['artist']['#text'], recent_track['name'], playcount))
else:
willie.say(u'\u266A' + ' %s - %s (%s plays)' % (recent_track['artist']['#text'], recent_track['name'], playcount))
except KeyError:
willie.say("Couldn't find any recent tracks")
示例2: mw_snippet
def mw_snippet(server, query, bot):
"""
Retrives a snippet of the specified length from the given page on the given
server.
"""
if bot.config.lang == 'ca':
snippet_url = ('https://ca.wikipedia.org/w/api.php?format=json'
'&action=query&prop=extracts&exintro&explaintext'
'&exchars=300&redirects&titles=')
elif bot.config.lang == 'es':
snippet_url = ('https://es.wikipedia.org/w/api.php?format=json'
'&action=query&prop=extracts&exintro&explaintext'
'&exchars=300&redirects&titles=')
else:
snippet_url = ('https://en.wikipedia.org/w/api.php?format=json'
'&action=query&prop=extracts&exintro&explaintext'
'&exchars=300&redirects&titles=')
if bot.config.lang == 'ca' or bot.config.lang == 'es':
snippet_url += web.quote(query.encode('utf-8'))
else:
snippet_url += web.quote(query.encode('cp1252'))
snippet = json.loads(web.get(snippet_url))
snippet = snippet['query']['pages']
# For some reason, the API gives the page *number* as the key, so we just
# grab the first page number in the results.
snippet = snippet[snippet.keys()[0]]
return snippet['extract']
示例3: search
def search(title):
response = '[{}]'
if is_integer(title.strip()):
response = web.get('https://mal-api.test.ramblingahoge.net/anime/'+web.quote(title), verify_ssl=False)
return json.loads('['+response+']')
else:
response = web.get('https://mal-api.test.ramblingahoge.net/anime/search?q='+web.quote(title), verify_ssl=False)
return json.loads(response)
示例4: lastfm
def lastfm(bot, trigger):
user = trigger.group(2)
apikey = str(bot.config.lastfm.apikey)
if not (user and user != ''):
user = bot.db.get_nick_value(trigger.nick, 'lastfm_user')
if not user:
bot.reply(render_error("Invalid username given or no username set. "
"Use {}fmset to set a username.".format(bot.config.core.prefix), "lfm"))
return
# username variable prepared for insertion into REST string
quoted_user = web.quote(user)
# json formatted output for recent track
recent_page = web.get(
"http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&format=json" % (
quoted_user, apikey))
try:
recent_track = json.loads(recent_page)['recenttracks']['track'][0]
except KeyError:
return bot.say(render_error("Failed to fetch user data", "lastfm"))
#artist and track name pulled from recent_track
quoted_artist = web.quote(recent_track['artist']['#text'])
quoted_track = web.quote(recent_track['name'])
#json formatted track info
trackinfo = requests.get(
"http://ws.audioscrobbler.com/2.0/?method=track.getInfo&artist=%s&track=%s&username=%s&api_key=%s&format=json" % (
quoted_artist, quoted_track, quoted_user, apikey))
if 'track' in trackinfo.json():
trackinfo = trackinfo.json()['track']
try:
playcount = trackinfo['userplaycount']
except KeyError:
playcount = "unknown"
loved = int(trackinfo['userloved'])
else:
loved = 0
playcount = 'Unknown'
try:
if loved > 0:
prefix = '\x035' + u'\u2665' + '\x03'
else:
prefix = '\u266A'
bot.say(render(items=[
EntityGroup([Entity("LastFM")]),
EntityGroup([
Entity("{} {}".format(prefix, recent_track['artist']['#text'])),
Entity(recent_track['name'])
]),
EntityGroup([Entity("Plays", playcount)])
]))
except KeyError:
bot.say(render_error("Couldn't find any recent tracks", "lastfm"))
示例5: mw_search
def mw_search(server, query, num, bot):
"""
Searches the specified MediaWiki server for the given query, and returns
the specified number of results.
"""
search_url = ('http://%s/w/api.php?format=json&action=query'
'&list=search&srlimit=%d&srprop=timestamp&srwhat=text'
'&srsearch=') % (server, num)
if bot.config.lang == 'ca' or bot.config.lang == 'es':
search_url += web.quote(query.encode('utf-8'))
else:
search_url += web.quote(query.encode('cp1252'))
query = json.loads(web.get(search_url))
query = query['query']['search']
return [r['title'] for r in query]
示例6: wa
def wa(willie, trigger):
"""Wolfram Alpha calculator"""
if not trigger.group(2):
return willie.reply("No search term.")
query = trigger.group(2)
uri = 'http://tumbolia.appspot.com/wa/'
try:
answer = web.get(uri + web.quote(query.replace('+', '%2B')), 45)
except timeout as e:
return willie.say('[WOLFRAM ERROR] Request timed out')
if answer:
answer = answer.decode('string_escape')
answer = HTMLParser.HTMLParser().unescape(answer)
#This might not work if there are more than one instance of escaped
#unicode chars But so far I haven't seen any examples of such output
#examples from Wolfram Alpha
match = re.search('\\\:([0-9A-Fa-f]{4})', answer)
if match is not None:
char_code = match.group(1)
char = unichr(int(char_code, 16))
answer = answer.replace('\:' + char_code, char)
waOutputArray = string.split(answer, ";")
if(len(waOutputArray) < 2):
willie.say('[WOLFRAM ERROR]' + answer)
else:
willie.say('[WOLFRAM] ' + waOutputArray[0] + " = "
+ waOutputArray[1])
waOutputArray = []
else:
willie.reply('Sorry, no result.')
示例7: duck_search
def duck_search(query):
query = query.replace('!', '')
query = web.quote(query)
uri = 'http://duckduckgo.com/html/?q=%s&kl=uk-en' % query
bytes = web.get(uri)
m = r_duck.search(bytes)
if m: return web.decode(m.group(1))
示例8: bing_search
def bing_search(query, lang='en-GB'):
query = web.quote(query)
base = 'http://www.bing.com/search?mkt=%s&q=' % lang
bytes = web.get(base + query)
m = r_bing.search(bytes)
if m:
return m.group(1)
示例9: wiktionary
def wiktionary(word):
bytes = web.get(uri % web.quote(word.encode('utf-8')))
bytes = r_ul.sub('', bytes)
mode = None
etymology = None
definitions = {}
for line in bytes.splitlines():
if 'id="Etymology"' in line:
mode = 'etymology'
elif 'id="Noun"' in line:
mode = 'noun'
elif 'id="Verb"' in line:
mode = 'verb'
elif 'id="Adjective"' in line:
mode = 'adjective'
elif 'id="Adverb"' in line:
mode = 'adverb'
elif 'id="Interjection"' in line:
mode = 'interjection'
elif 'id="Particle"' in line:
mode = 'particle'
elif 'id="Preposition"' in line:
mode = 'preposition'
elif 'id="' in line:
mode = None
elif (mode == 'etmyology') and ('<p>' in line):
etymology = text(line)
elif (mode is not None) and ('<li>' in line):
definitions.setdefault(mode, []).append(text(line))
if '<hr' in line:
break
return etymology, definitions
示例10: wa
def wa(bot, trigger):
"""Wolfram Alpha calculator"""
if not trigger.group(2):
return bot.reply("No search term.")
query = trigger.group(2)
uri = 'http://tumbolia.appspot.com/wa/'
try:
answer = web.get(uri + web.quote(query.replace('+', '%2B')), 45)
except timeout as e:
return bot.say('[WOLFRAM ERROR] Request timed out')
if answer:
answer = answer.decode('string_escape')
answer = HTMLParser.HTMLParser().unescape(answer)
# This might not work if there are more than one instance of escaped
# unicode chars But so far I haven't seen any examples of such output
# examples from Wolfram Alpha
match = re.search('\\\:([0-9A-Fa-f]{4})', answer)
if match is not None:
char_code = match.group(1)
char = unichr(int(char_code, 16))
answer = answer.replace('\:' + char_code, char)
waOutputArray = string.split(answer, ";")
if(len(waOutputArray) < 2):
if(answer.strip() == "Couldn't grab results from json stringified precioussss."):
# Answer isn't given in an IRC-able format, just link to it.
bot.say('[WOLFRAM]Couldn\'t display answer, try http://www.wolframalpha.com/input/?i=' + query.replace(' ', '+'))
else:
bot.say('[WOLFRAM ERROR]' + answer)
else:
bot.say('[WOLFRAM] ' + waOutputArray[0] + " = "
+ waOutputArray[1])
waOutputArray = []
else:
bot.reply('Sorry, no result.')
示例11: py
def py(willie, trigger):
"""Evaluate a Python expression."""
query = trigger.group(2).encode('utf-8')
uri = 'http://tumbolia.appspot.com/py/'
answer = web.get(uri + web.quote(query))
if answer:
willie.say(answer)
else: willie.reply('Sorry, no result.')
示例12: logHTML_end
def logHTML_end(channel):
logfile = codecs.open(meeting_log_path + channel + '/' + figure_logfile_name(channel) + '.html', 'a', encoding='utf-8')
current_time = time.strftime('%H:%M:%S', time.gmtime())
logfile.write('</ul>\n<h4>Meeting ended at %s UTC</h4>\n' % current_time)
plainlog_url = meeting_log_baseurl + quote(channel + '/' + figure_logfile_name(channel) + '.log')
logfile.write('<a href="%s">Full log</a>' % plainlog_url)
logfile.write('\n</body>\n</html>')
logfile.close()
示例13: google_ajax
def google_ajax(query):
"""Search using AjaxSearch, and return its JSON."""
if isinstance(query, unicode):
query = query.encode('utf-8')
uri = 'http://ajax.googleapis.com/ajax/services/search/web'
args = '?v=1.0&safe=off&q=' + web.quote(query)
bytes = web.get(uri + args)
return json.loads(bytes)
示例14: duck_api
def duck_api(query):
uri = web.quote(query)
uri = 'http://api.duckduckgo.com/?q=%s&format=json&no_html=1&no_redirect=1'%query
results = json.loads(web.get(uri))
print results
if results['Redirect']:
return results['Redirect']
else:
return None
示例15: py
def py(bot, trigger):
"""Evaluate a Python expression."""
query = trigger.group(2)
uri = 'http://tumbolia.appspot.com/py/'
answer = web.get(uri + web.quote(query))
if answer:
bot.say(answer)
else:
bot.reply('Sorry, no result.')