Python ljust not displaying properly when including a lin - python

I am using Django creating a site for records for football teams, I have a "pretty" display with CSS, etc, but as a backup / old school version I am trying to have the code write the information to a basic .html file that is using rjust, ljust, etc to format text. In the code below if I remove the link code, and just display the string for the team's name everything lines up properly. Once I add the HTML for the link though the columns do not line up and are completely out of whack. What have I done wrong?
standings = Team.objects.filter(active=True).order_by('-wp')
output += '<pre>\n'
output += '%s %s %s %s\n' % (str('Rk').rjust(3), str('Team').ljust(50), str('W').rjust(2), str('L').rjust(2))
output += '%s %s %s %s\n' % (str('--').rjust(3), str('----').ljust(50), str('-').rjust(2), str('-').rjust(2))
for row in mpi:
the_team = "%s" % (row.slug, row.name)
output += '%s %s %s %s\n' % (str(row.rank).rjust(3), str(the_team).ljust(50), str(row.won).rjust(2), str(row.lost).rjust(2))
output += '</pre>'

The string "%s" contains some characters that aren't rendered on browser, you're formatting the source code, not the visualization.
Replace str(row.the_team).ljust(50) by str(row.the_team).ljust(50+len(row.slug)+15) because there are 15 invisible chars (ie. ) plus the slug.
Update: You may want to remove some str. If some value is already a string, you didn't need to (re)transform it in string again.. You may also split long lines in shorten ones.
output = '<pre>\n'
output += '%s %s%s%s\n' % ('Rk'.rjust(3), 'Team'.ljust(50), 'W'.rjust(2), 'L'.rjust(2))
output += '%s %s%s%s\n' % ('--'.rjust(3), '----'.ljust(50), '-'.rjust(2), '-'.rjust(2))
for team in teams:
link = '%s' % (team.slug, team.name)
link = link.ljust(50 + len(team.slug) + 15)
rank, won, lost = str(team.rank).rjust(3), str(team.won).rjust(2), str(team.lost).rjust(2)
output += '%s %s%s%s\n' % (rank, link, won, lost)
output += '</pre>'
print output

Related

How do I utter dynamic message with hyperlink attached in Rasa X?

How do I utter a message, displaying results based on a datasheet, and attach a hyperlink within the text? Example of what I am trying to achieve:
num = phone_format(str(sheet["" + chr(ord(requested_info_column)+1) + "{}".format(row)].value))
dispatcher.utter_message(text="The " + column_names[requested_info_column]
+ " for the " + str(sheet["B{}".format(row)].value) + " project is "
+ str(sheet["" + str(requested_info_column) + "{}".format(row)].value)
+ " and can be reached at " + num)
formatting method:
def phone_format(n):
formatNum = '({}){}-{}'.format(n[0:3], n[3:6], n[6:])
hypNum = '%s' % (n, formatNum)
return hypNum
The issue I am having is that Rasa X displays the string, with the correct data, but the hyperlink is not attached to the phone number.
Displaying links in the front end is different for different platforms. Rasa X uses Markdown Format to display the links.
So, instead of the normal anchor tag, you need to use Markdown link format for display.
Change
hypNum = '%s' % (n, formatNum)
to this
hypNum = '[%s](tel:%s)' % (formatNum,n)
Hope this solves your issue.

Python Wikipedia library

I'm using python library Wikipedia to parse data. When its get to the second part of the code I'm getting page errors.Page Errors
import wikipedia
print ("1: Searching Wikipedia for 'List of Lexus vehicles'")
try:
print (wikipedia.page('List of Lexus'))
print ('-' * 60)
except wikipedia.exceptions.DisambiguationError as e:
print (str(e))
print ('+' * 60)
print ('DisambiguationError: The page name is ambiguous')
print
print ("2: Searching Wikipedia for 'List of Lexus (vehicles)'")
print (wikipedia.page('List of Lexus_(vehicles)'))
print
result = wikipedia.page('List of Lexus_(vehicles)').content.encode('UTF8')
print ("3: Result of searching Wikipedia for 'List of Lexus_(vehicles)':")
print (result)
print
lexus_count = result.count('ct','lfa','rx')
print
print ("The Wikipedia page for 'Lexus_(company)' has " + \
"{} occurrences of the word 'Lexus'".format(lexus_count))
print
Updated
I'm able to parse page data but getting Type error on count
23 print
24
25 lexus_count = result.count('ct','lfa','rx')
26 print
TypError: slice indices must be integers or None or have an __index__ method
There was multiple issues with your program. Here is an updated program, with the errors fixed and marked.
import wikipedia
print ("1: Searching Wikipedia for 'Lexus'")
try:
print (wikipedia.page('Lexus'))
print ('-' * 60)
except wikipedia.exceptions.DisambiguationError as e:
print (str(e))
print ('+' * 60)
print ('DisambiguationError: The page name is ambiguous')
print
print ("2: Searching Wikipedia for 'Lexus (company)'")
result = wikipedia.page('Lexus (company)')
# ERR; PAGE NAME SEPARATED BY SPACE NOT WITH AN UNDERSCORE
# <> PAGE ERROR AS PAGE WILL NOT BE FOUND.
print (result)
print
result = result.content
print ("3: Result of searching Wikipedia for 'Lexus_(company)':")
print (result)
print
lexus_count = result.count('Lexus')
# changed variable name from orange_count -> lexus_count, as referenced in the print function below.
# you were counting for 'lexus' you will not find any occurrences as this function is case sensitive.
print
print ("The Wikipedia page for 'Lexus_(company)' has " + \
"{} occurrences of the word 'Lexus'".format(lexus_count))
print
Hope this helps.
Which page error exactly are you getting?
According to the wikipedia documentation: https://wikipedia.readthedocs.io/en/latest/quickstart.html#quickstart
But watch out - wikipedia.summary will raise a DisambiguationError if the page is a disambiguation page, or a PageError if the page doesn’t exist (although by default, it tries to find the page you meant with suggest and search.):

Python: Google Contacts API only retrieving 3 contacts

I am new to Python and to the Google APIs.
I have the following code from https://developers.google.com/google-apps/contacts/v3/?hl=en:
def PrintAllContacts(gd_client):
feed = gd_client.GetContacts()
for i, entry in enumerate(feed.entry):
print '\n%s %s' % (i+1, entry.name.full_name.text)
if entry.content:
print ' %s' % (entry.content.text)
# Display the primary email address for the contact.
for email in entry.email:
if email.primary and email.primary == 'true':
print ' %s' % (email.address)
# Show the contact groups that this contact is a member of.
for group in entry.group_membership_info:
print ' Member of group: %s' % (group.href)
# Display extended properties.
for extended_property in entry.extended_property:
if extended_property.value:
value = extended_property.value
else:
value = extended_property.GetXmlBlob()
print ' Extended Property - %s: %s' % (extended_property.name, value)
This is only returning 3 contacts out of c. 850. Any thoughts, anyone?
This works:
def PrintAllContacts(gc):
max_results = 20000
start_index = 1
query = gdata.contacts.client.ContactsQuery()
query.max_results = max_results
query.start_index = start_index
feed = gc.GetContacts(q=query)
print len(feed.entry)
for e in feed.entry:
print e.name
for email in e.email:
print email.address
Useful link: https://gdata-python-client.googlecode.com/hg/pydocs/gdata.contacts.data.html#ContactEntry

django returns none on web page

when I run this function in Django my output is none. what is wrong with the news() function?
Code:
import feedparser
from django.http import HttpResponse
def news():
YahooContent = feedparser.parse ("http://news.yahoo.com/rss/")
for feed in YahooContent.entries:
print feed.published
print feed.title
print feed.link + "\n"
return
def html(request):
html = "<html><body> %s </body></html>" % news()
return HttpResponse(html)
Error:
webpage shows None
You are printing the results, not returning them. In fact, the return statement will return None, just like all methods that don't have a return statement.
You should build the string in your method itself, like this:
def html(request):
head = '<html><body>'
foot = '</body></html>'
entries = []
for entry in feedparser.parse("http://news.yahoo.com/rss/").entries:
entries.append('{}<br />{}<br />{}<br />'.format(entry.published,
entry.title, entry.link))
return HttpResponse(head+''.join(entries)+foot)
Can you explain your code a little bit?
Imagine you have a list of "entries", like this:
entries = [a, b, c]
Each entry has a .published, .title, .link attribute that you want to print as a list in HTML.
You can do this easily by looping through it and using the print statement:
print('<ul>')
for entry in entries:
print('<li>{0.published} - {0.title} - {0.link}</li>'.format(entry))
print('</ul>')
However, what we need here is to send this data to the browser as a HTML response. We can build the HTML string by replacing print with a string that we keep adding to, like this:
result = '<ul>'
for entry in entries:
result += '<li>{0.published} - {0.title} - {0.link}</li>'.format(entry)
result += '</ul>'
This will work but is inefficient and slow, it is better to collect the strings in a list, and then join them together. This is what I did in my original answer:
result = ['<ul>']
for entry in entries:
result.append('<li>{0.published} - {0.title} - {0.link}</li>'.format(entry))
result.append('</li>')
Then I just joined them all up with a header and a footer, and then combined each individual string in the list with a space, and returned it as the response:
return HttpResponse('<html><body>'+''.join(result)+'</body></html>')
obviously your news() method returns nothing..
The right way should be:
def news():
YahooContent = feedparser.parse ("http://news.yahoo.com/rss/")
result = ''
for feed in YahooContent.entries:
result += feed.published + '\n'
result += feed.title + '\n'
result += feed.link + "\n"
return result
def html(request):
html = "<html><body> %s </body></html>" % news()
return HttpResponse(html)

Need to handle keyerror exception python

I'm getting a keyerror exception when I input a player name here that is not in the records list. I can search it and get back any valid name, but if I input anything else, i get a keyerror. I'm not really sure how to go about handling this since it's kindof confusing already dealing with like 3 sets of data created from parsing my file.
I know this code is bad I'm new to python so please excuse the mess - also note that this is a sortof test file to get this functionality working, which I will then write into functions in my real main file. Kindof a testbed here, if that makes any sense.
This is what my data file, stats4.txt, has in it:
[00000] Cho'Gath - 12/16/3 - Loss - 2012-11-22
[00001] Fizz - 12/5/16 - Win - 2012-11-22
[00002] Caitlyn - 13/4/6 - Win - 2012-11-22
[00003] Sona - 4/5/9 - Loss - 2012-11-23
[00004] Sona - 2/1/20 - Win - 2012-11-23
[00005] Sona - 6/3/17 - Loss - 2012-11-23
[00006] Caitlyn - 14/2/16 - Win - 2012-11-24
[00007] Lux - 10/2/14 - Win - 2012-11-24
[00008] Sona - 8/1/22 - Win - 2012-11-27
Here's my code:
import re
info = {}
records = []
search = []
with open('stats4.txt') as data:
for line in data:
gameid = [item.strip('[') for item in line.split(']')]
del gameid[-1]
gameidstr = ''.join(gameid)
gameid = gameidstr
line = line[7:]
player, stats, outcome, date = [item.strip() for item in line.split('-', 3)]
stats = dict(zip(('kills', 'deaths', 'assists'), map(int, stats.split('/'))))
date = tuple(map(int, date.split('-')))
info[player] = dict(zip(('gameid', 'player', 'stats', 'outcome', 'date'), (gameid, player, stats, outcome, date)))
records.append(tuple((gameid, info[player])))
print "\n\n", info, "\n\n" #print the info dictionary just to see
champ = raw_input() #get champion name
#print info[champ].get('stats').get('kills'), "\n\n"
#print "[%s] %s - %s/%s/%s - %s-%s-%s" % (info[champ].get('gameid'), champ, info[champ].get('stats').get('kills'), info[champ].get('stats').get('deaths'), info[champ].get('stats').get('assists'), info[champ].get('date')[0], info[champ].get('date')[1], info[champ].get('date')[2])
#print "\n\n"
#print info[champ].values()
i = 0
for item in records: #this prints out all records
print "\n", "[%s] %s - %s/%s/%s - %s - %s-%s-%s" % (records[i][0], records[i][1]['player'], records[i][1]['stats']['kills'], records[i][1]['stats']['deaths'], records[i][1]['stats']['assists'], records[i][1]['outcome'], records[i][1]['date'][0], records[i][1]['date'][1], records[i][1]['date'][2])
i = i + 1
print "\n" + "*" * 50
i = 0
for item in records:
if champ in records[i][1]['player']:
search.append(records[i][1])
else:
pass
i = i + 1
s = 0
if not search:
print "no availble records" #how can I get this to print even if nothing is inputted in raw_input above for champ?
print "****"
for item in search:
print "\n[%s] %s - %s/%s/%s - %s - %s-%s-%s" % (search[s]['gameid'], search[s]['player'], search[s]['stats']['kills'], search[s]['stats']['deaths'], search[s]['stats']['assists'], search[s]['outcome'], search[s]['date'][0], search[s]['date'][1], search[s]['date'][2])
s = s + 1
I tried setting up a Try; Except sort of thing but I couldn't get any different result when entering an invalid player name. I think I could probably set something up with a function and returning different things if the name is present or not but I think I've just gotten myself a bit confused. Also notice that no match does indeed print for the 8 records that aren't matches, though thats not quite how I want it to work. Basically I need to get something like that for any invalid input name, not just a valid input that happens to not be in a record in the loop.
Valid input names for this data are:
Cho'Gath, Fizz, Caitlyn, Sona, or Lux - anything else gives a keyerror, thats what I need to handle so it doesn't raise an error and instead just prints something like "no records available for that champion" (and prints that only once, rather then 8 times)
Thanks for any help!
[edit] I was finally able to update this code in the post (thank you martineau for getting it added in, for some reason backticks aren't working to block code and it was showing up as bold normal text when i pasted. Anyways, look at if not search, how can I get that to print even if nothing is entered at all? just pressing return on raw_input, currently it prints all records after **** even though i didn't give it any search champ
where is your exact error occurring?
i'm just assuming it is when champ = raw_input() #get champion name
and then info[champ]
you can either check if the key exists first
if champ not in info:
print 'no records avaialble'
or use get
if info.get(champ)
or you can just try and access the key
try:
info[champ]
# do stuff
except KeyError:
print 'no records available'
the more specific you can be in your question the better, although you explained your problem you really didn't include any specifics Please always include a traceback if available, and post the relevant code IN your post not on a link.
Here's some modifications that I think address your problem. I also reformatted the code to make it a little more readable. In Python it's possible to continue long lines onto the next either by ending with a \ or just going to the next line if there's an unpaired '(' or '[' on the previous line.
Also, the way I put code in my questions or answer here is by cutting it out of my text editor and then pasting it into the edit window, after that I make sure it's all selected and then just use the {} tool at the top of edit window to format it all.
import re
from pprint import pprint
info = {}
records = []
with open('stats4.txt') as data:
for line in data:
gameid = [item.strip('[') for item in line.split(']')]
del gameid[-1]
gameidstr = ''.join(gameid)
gameid = gameidstr
line = line[7:]
player, stats, outcome, date = [item.strip() for item in line.split('-', 3)]
stats = dict(zip(('kills', 'deaths', 'assists'), map(int, stats.split('/'))))
date = tuple(map(int, date.split('-')))
info[player] = dict(zip(('gameid', 'player', 'stats', 'outcome', 'date'),
(gameid, player, stats, outcome, date)))
records.append(tuple((gameid, info[player])))
#print "\n\n", info, "\n\n" #print the info dictionary just to see
pprint(info)
champ = raw_input("Champ's name: ") #get champion name
#print info[champ].get('stats').get('kills'), "\n\n"
#print "[%s] %s - %s/%s/%s - %s-%s-%s" % (
# info[champ].get('gameid'), champ, info[champ].get('stats').get('kills'),
# info[champ].get('stats').get('deaths'), info[champ].get('stats').get('assists'),
# info[champ].get('date')[0], info[champ].get('date')[1],
# info[champ].get('date')[2])
#print "\n\n"
#print info[champ].values()
i = 0
for item in records: #this prints out all records
print "\n", "[%s] %s - %s/%s/%s - %s - %s-%s-%s" % (
records[i][0], records[i][1]['player'], records[i][1]['stats']['kills'],
records[i][1]['stats']['deaths'], records[i][1]['stats']['assists'],
records[i][1]['outcome'], records[i][1]['date'][0],
records[i][1]['date'][1], records[i][1]['date'][2])
i = i + 1
print "\n" + "*" * 50
i = 0
search = []
for item in records:
if champ in records[i][1]['player']:
search.append(records[i][1])
i = i + 1
if not search:
print "no match"
exit()
s = 0
for item in search:
print "\n[%s] %s - %s/%s/%s - %s - %s-%s-%s" % (search[s]['gameid'],
search[s]['player'], search[s]['stats']['kills'],
search[s]['stats']['deaths'], search[s]['stats']['assists'],
search[s]['outcome'], search[s]['date'][0], search[s]['date'][1],
search[s]['date'][2])
s = s + 1

Categories