2016-03-27 35 views
-2

打开文件mbox-short.txt并逐行读取它。当你发现开头“从”类似下面的一行:Python错误:TypeError:'int'对象不可调用

From [email protected] Sat Jan 5 09:14:16 2008 

您将采用分体式()解析从线和线打印出的第二个字(即人的全部地址谁发了消息)。然后在最后打印一个计数。

提示:确保不要包含以'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 

[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 

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 

我不知道为什么我收到这个回溯。

+1

脚本的顶部有'count = 0',这是不可调用的,即function/class/etc。你期望做什么? – Reti43

+0

'count'是一个变量,而不是函数。我认为如果你只是使用:'print'在文件中有',件[1]',''作为第一个单词''它应该工作...... – thefoxrocks

+0

正如其他答案所说:'count'是不是一个函数,所以我不明白你为什么期望它能够工作。 –

回答

0

正如有关评论也提到,count未列为a功能 - 相反,它是一个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 
+1

顺便说一句,您在输出中添加了额外的空格。 – TigerhawkT3

+0

已编辑。谢谢!我在一段时间内没有使用'print'的笨重语句版本... –

+1

它在Python 3中会以同样的方式发生。默认分隔符是空格。 – TigerhawkT3

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, 
+0

非常感谢你,帮助我解决了大部分问题。 – Roy

相关问题