Re: [Tutor] Mailbox

ltc.hotspot at gmail.com ltc.hotspot at gmail.com
Thu Jul 30 21:00:52 CEST 2015


Hi Cameron,

New revision code:


count = 0
fn = raw_input("Enter file name: ")
if len(fn) < 1 : fname = "mbox-short.txt"
for line in fn:
  if 'From' in line.split()[0]: count += 1
print "There are %d lines starting with From" % count
print len(line)
fn = open(fname)
print "There were", count, "lines in the file with From as the first word"




Syntax message produced by iPython interperter:


NameError                                 Traceback (most recent call last)
C:\Users\vm\Desktop\apps\docs\Python\assinment_8_5_v_2.py in <module>()
      6 print "There are %d lines starting with From" % count
      7 print len(line)
----> 8 fn = open(fname)
      9 print "There were", count, "lines in the file with From as the first wor
d"


NameError: name 'fname' is not defined


In [16]:



Question:


Why is fname = "mbox-short.txt" not loading the sample data?


Sample data file is located at  http://www.pythonlearn.com/code/mbox-short.txt


Regards,
Hal






Sent from Surface





From: Cameron Simpson
Sent: ‎Wednesday‎, ‎July‎ ‎29‎, ‎2015 ‎7‎:‎01‎ ‎PM
To: Tutor at python.org





On 29Jul2015 21:55, ltc.hotspot at gmail.com <ltc.hotspot at gmail.com> wrote:
>I have a second and unrelated question:
>
>I tried to work backward  to see if there is a logic error associated with a variable is being skipped over:
>
>#top of code, initialize variable
>output_list = ["default"]

Curious: why not just make this an empty list: []

[...snip...]
>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.startswith('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"
[...snip...]

My first observation would be that "count = count + 1" is not inside the loop.  
That means that it fires just once, _after_ the loop. So it will always be 1.

Also, what is the purpose of this line:

  line = line.split()

Cheers,
Cameron Simpson <cs at zip.com.au>
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150730/ff45dcd5/attachment.html>


More information about the Python-list mailing list