[Tutor] String Attribute
ltc.hotspot at gmail.com
ltc.hotspot at gmail.com
Sat Aug 1 01:59:04 CEST 2015
Sent from Surface
From: Alan Gauld
Sent: Friday, July 31, 2015 4:54 PM
To: Tutor at python.org
On 31/07/15 19:57, ltc.hotspot at gmail.com wrote:
> for line in fh:
> line2 = line.strip()
> line3 = line2.split()
> line4 = line3
You need to check that there actually is something
in the list to access. If you get a line with only
one word in it, or even a blank line this will fail.
→→Apparently, the data content in the file is lost from the address sort function to line2? :
In : print line3
In : print line2.split()
In : print line2
In : print line.strip()
In : print fh
<open file 'mbox-short.txt', mode 'r' at 0x00000000035CB0C0>
In : print addresses
set(['1.0', 'source at collab.sakaiproject.org;', 'Jan', 'mail.umich.edu', 'Innocen
t', '0.0000', 'CMU', 'frankenstein.mail.umich.edu', '0.8475', 'from', 'source at co
llab.sakaiproject.org', '05', '<200801051412.m05ECIaH010327 at nakamura.uits.iupui.
edu>', 'flawless.mail.umich.edu', '5', 'nakamura.uits.iupui.edu:', 'shmi.uhi.ac.
uk', '7bit', 'text/plain;', '<source at collab.sakaiproject.org>;', 'Sat,', 'nakamu
ra.uits.iupui.edu', 'paploo.uhi.ac.uk', 'FROM', 'holes.mr.itd.umich.edu', '(from
', '<postmaster at collab.sakaiproject.org>', '[sakai]', 'stephen.marquard at uct.ac.z
→ Latest code printout:
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
addresses = set()
for line in fh:
line2 = line.strip()
line3 = line2.split()
line4 = line3
count = count + 1
print "There were", count, "lines in the file with From as the first word"
> count = count + 1
> print "There were", count, "lines in the file with From as the first word"
Despite what you print you don't know that its true anymore.
You have removed the code that tested for the first
word being "From". You should put that check back in your code.
> →I entered different index ranges from  to 
I'm not sure what  means in this case? It should be a syntax error
as you show below.
> In : print line3
> File "<ipython-input-34-7bf39294000a>", line 1
> print line3
> SyntaxError: invalid syntax
See, that's not an IndexError. They are different and have different
causes. A syntax error means your code is not valid Python. An
IndexError means the code is valid but its trying to access
something that doesn't exist.
→Question: I think the problem is in the placement of the address set: The addresses = set()?
No it has nothing to do with that. The set is not
involved in this operation at this point.
To debug these kinds of errors insert a print statement
above the error line. In this case:
→→ Read printout above
That will show you what the data looks like and you can tell
whether line3 makes any kind of sense.
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
More information about the Tutor