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: tu...@python.org
On 29Jul2015 21:55, ltc.hots...@gmail.com <ltc.hots...@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 <c...@zip.com.au>
_______________________________________________
Tutor maillist - tu...@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
--
https://mail.python.org/mailman/listinfo/python-list