[Tutor] String Attribute
Alan Gauld
alan.gauld at btinternet.com
Wed Jul 29 11:17:31 CEST 2015
On 29/07/15 00:33, ltc.hotspot at gmail.com wrote:
> Hi Everyone:
>
>
> What is the source of the syntax error to the String Attribute?
Normally I'd ask you to post the full text of any errors.
They usually contain a lot of useful information. They
also help us identify which syntax error you are asking
about in the case where there are several! :-)
But in your case it seems you are running the code in an online debugger
so you may not have seen the full error text. Although,
even there, it gives more information that you posted, namely:
AttributeError: 'str' object has no attribute 'startwith'
So it's not a syntax error but an attribute error...
Your error is with the attribute startwith, which doesn't exist.
To check the attributes of a string, type dir(str) at a >>> prompt.
(I assume you have access to one of those somewhere?)
You will see that you mis-spelled startswith.
However, your code has several other problems...
> Go to the following URL links and view a copy of the raw data file code and sample data:
>
> 1.) http://tinyurl.com/p2xxxhl
> 2.) http://tinyurl.com/nclg6pq
If its short (<100 lines?) just include the code in the message.
Here it is:
count = 0
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
for line in fname:
line = line.strip()
if not line.startwith('From '): continue
line = line.split()
count = count + 1
print len(line)
fh = open(fname)
print "There were", count, "lines in the file with From as the first word"
You set the filename and then iterate over the name.
I suspect you intended to iterate over the file contents?
To do that you need to open the file (which you do near
the end!) So something like:
with open(fname as in_file:
for line in in_file:
# do your stuff here
The next problem is that the last line of the loop holds the individual
elements of the split, but you throw that away when the loop goes back
to the top. You need to save the result somewhere so you can process it
after the loop completes.
For this specific example you could just indent the
count = count + 1
print len(line)
lines inside the loop. But that won't be enough to get you to your
final output of the email addresses.
> Here is the desired output:
> stephen.marquard at uct.ac.za
> louis at media.berkeley.edu
> ....
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list