打开文件mbox-short.txt并逐行读取。当您找到以“From”开头的行时,如下所示:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
您将使用split()解析From行,并打印出行中的第二个单词(即发送消息的人的整个地址)。然后在最后打印出一个计数。
提示:请确保不要包含以“发件人:”开头的行。
mbox-short.txt文件的链接: http://www.pythonlearn.com/code/mbox-short.txt
fopen = raw_input('Enter the file name you want to open: ')
fname = open(fopen)
line = 0
count = 0
pieces = 0
email = list()
for line in fname:
lines = line.rstrip()
if not line.startswith('From '):
continue
pieces = line.split()
print pieces[1]
print 'There were' ,count(pieces[1]), 'lines in the file with From as the first word
我设法得到正确的输出,直到最后一条打印消息。
执行:
Enter the file name you want to open: mbox-short.txt
louis@media.berkeley.edu
zqian@umich.edu
rjlowe@iupui.edu
zqian@umich.edu
rjlowe@iupui.edu
cwen@iupui.edu
cwen@iupui.edu
gsilver@umich.edu
gsilver@umich.edu
zqian@umich.edu
gsilver@umich.edu
wagnermr@iupui.edu
zqian@umich.edu
antranig@caret.cam.ac.uk
gopal.ramasammycook@gmail.com
david.horwitz@uct.ac.za
david.horwitz@uct.ac.za
david.horwitz@uct.ac.za
david.horwitz@uct.ac.za
stephen.marquard@uct.ac.za
louis@media.berkeley.edu
louis@media.berkeley.edu
ray@media.berkeley.edu
cwen@iupui.edu
cwen@iupui.edu
cwen@iupui.edu
Traceback (most recent call last):
print 'There were' ,count(pieces[1]), 'lines in the file with From as the first word'
TypeError: 'int' object is not callable
我不知道为什么我会收到这个追溯。
答案 0 :(得分:0)
'int' object is not callable
因为count = 0
然后是count(pieces[1])
。你有一个整数,你正在调用它。在此之后:
pieces = line.split()
print pieces[1]
添加:
count += 1
然后改变这个:
print 'There were' ,count(pieces[1]),
对此:
print 'There were', count,
答案 1 :(得分:0)
正如问题中的评论所提到的,count
未列为功能 - 相反,它是int
。你不能将pieces[1]
传递给它,并期望它能够神奇地增加它自己。
如果您真的想要这样计数,只需在循环浏览文件时更新计数。
fopen = raw_input('Enter the file name you want to open: ')
fname = open(fopen)
line = 0 # unnecessary
count = 0
pieces = 0 # also unnecessary
email = list() # also unnecessary
for line in fname:
lines = line.rstrip()
if not line.startswith('From '):
continue
pieces = line.split()
print pieces[1]
count = count + 1 # increment here - counts number of lines in file
print 'There were', count, 'lines in the file with From as the first word