本文整理汇总了Python中willie.web.quote函数的典型用法代码示例。如果您正苦于以下问题:Python quote函数的具体用法?Python quote怎么用?Python quote使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了quote函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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")
开发者ID:Gseoa,项目名称:willie-modules,代码行数:34,代码来源:lastfm.py
示例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']
开发者ID:FreuddyHS,项目名称:Granota,代码行数:29,代码来源:wikipedia.py
示例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)
开发者ID:meew0,项目名称:inumuta-modules,代码行数:8,代码来源:mal.py
示例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"))
开发者ID:ToTV,项目名称:willie,代码行数:52,代码来源:lfm.py
示例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]
开发者ID:FreuddyHS,项目名称:Granota,代码行数:15,代码来源:wikipedia.py
示例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.')
开发者ID:303i,项目名称:willie,代码行数:31,代码来源:calc.py
示例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))
开发者ID:Shokodemon,项目名称:willie,代码行数:7,代码来源:search.py
示例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)
开发者ID:atti92,项目名称:AtiBot,代码行数:7,代码来源:search.py
示例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
开发者ID:Shokodemon,项目名称:willie,代码行数:35,代码来源:wiktionary.py
示例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.')
开发者ID:DanUgore,项目名称:willie,代码行数:35,代码来源:calc.py
示例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.')
开发者ID:mrbysh,项目名称:willie,代码行数:8,代码来源:calc.py
示例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()
开发者ID:daubman,项目名称:willie,代码行数:8,代码来源:meetbot.py
示例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)
开发者ID:Shokodemon,项目名称:willie,代码行数:8,代码来源:search.py
示例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
开发者ID:Shokodemon,项目名称:willie,代码行数:9,代码来源:search.py
示例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.')
开发者ID:DanUgore,项目名称:willie,代码行数:9,代码来源:calc.py
示例16: suggest
def suggest(willie, trigger):
"""Suggest terms starting with given input"""
if not trigger.group(2):
return willie.reply("No query term.")
query = trigger.group(2).encode('utf-8')
uri = 'http://websitedev.de/temp-bin/suggest.pl?q='
answer = web.get(uri + web.quote(query).replace('+', '%2B'))
if answer:
willie.say(answer)
else: willie.reply('Sorry, no result.')
开发者ID:Shokodemon,项目名称:willie,代码行数:10,代码来源:search.py
示例17: wa
def wa(bot, trigger):
"""Wolfram Alpha calculator"""
if not trigger.group(2):
if bot.config.lang == 'ca':
return bot.reply("Res per buscar. Sintaxi: .wa <paraula|frase|operacio|...>.")
elif bot.config.lang == 'es':
return bot.reply("Nada para buscar. Sintaxis: .wa <palabra|frase|operacion|...>.")
else:
return bot.reply("Nothing to search. Syntax: .wa <word|sentence|operation|...>.")
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:
if bot.config.lang == 'ca':
return bot.say('[WOLFRAM ERROR] Temps d\'espera excedit.')
elif bot.config.lang == 'es':
return bot.say('[WOLFRAM ERROR] Tiempo de espera excedido.')
else:
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.
if bot.config.lang == 'ca':
bot.say('[WOLFRAM] No hi ha cap resposta disponible. Prova amb http://www.wolframalpha.com/input/?i=' + query.replace(' ', '+'))
elif bot.config.lang == 'es':
bot.say('[WOLFRAM] No hay ninguna respusta disponible. Prueba con http://www.wolframalpha.com/input/?i=' + query.replace(' ', '+'))
else:
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:
if bot.config.lang == 'ca':
bot.reply(u"Sense resultats.")
elif bot.config.lang == 'es':
bot.repy(u"Sin resultados.")
else:
bot.reply('Sorry, no result.')
开发者ID:NeoMahler,项目名称:Granota,代码行数:55,代码来源:calc.py
示例18: duck_api
def duck_api(query):
if '!bang' in query.lower():
return 'https://duckduckgo.com/bang.html'
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))
if results['Redirect']:
return results['Redirect']
else:
return None
开发者ID:BOFHers,项目名称:willie,代码行数:11,代码来源:search.py
示例19: translate
def translate(text, input='auto', output='en'):
raw = False
if unicode(output).endswith('-raw'):
output = output[:-4]
raw = True
headers = {
'User-Agent': 'Mozilla/5.0' +
'(X11; U; Linux i686)' +
'Gecko/20071127 Firefox/2.0.0.11'
}
input, output = web.quote(input), web.quote(output)
if sys.version_info.major < 3:
try:
if text is not text.encode("utf-8"):
text = text.encode("utf-8")
except:
pass
text = web.quote(text)
result = web.get('http://translate.google.com/translate_a/t?' +
('client=t&sl=%s&tl=%s' % (input, output)) +
('&q=%s' % text), 40, headers=headers)
if sys.version_info.major>=3:
result = result.decode()
while ',,' in result:
result = result.replace(',,', ',null,')
result = result.replace('[,', '[null,')
data = json.loads(result)
if raw:
return str(data), 'en-raw'
try:
language = data[2] # -2][0][0]
except:
language = '?'
return ''.join(x[0] for x in data[0]), language
开发者ID:antiman,项目名称:willie,代码行数:41,代码来源:translate.py
示例20: py
def py(bot, trigger):
"""Evaluate a Python expression."""
if not trigger.group(2):
return bot.say("Se necesita una expresión para evaluar")
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('Sin resultado correcto.')
开发者ID:InteliBOT,项目名称:pyDreamBot,代码行数:12,代码来源:calc.py
注:本文中的willie.web.quote函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论