Python错误:TypeError:“int”对象不可调用

Python错误:TypeError:“int”对象不可调用,python,parsing,split,typeerror,Python,Parsing,Split,Typeerror,打开文件mbox-short.txt并逐行读取。当您找到以“From”开头的行时,如以下行所示: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 您将使用split解析From行,并打印出行中的第二个单词,即发送消息的人的完整地址。然后在最后打印一个计数 提示:确保不包括以“From:”开头的行 mbox-short.txt文件的链接: 我设法得到了正确的输出,直到最后一条打印消息 执行: Enter the file nam

打开文件mbox-short.txt并逐行读取。当您找到以“From”开头的行时,如以下行所示:

From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008
您将使用split解析From行,并打印出行中的第二个单词,即发送消息的人的完整地址。然后在最后打印一个计数

提示:确保不包括以“From:”开头的行

mbox-short.txt文件的链接:

我设法得到了正确的输出,直到最后一条打印消息

执行:

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
我不知道为什么要得到这个回溯。

'int'对象不可调用,因为count=0,然后是countpieces[1]。你有一个整数,你正在调用它。在此之后:

pieces = line.split()
print pieces[1]
添加以下内容:

count += 1
然后改变这个:

print 'There were' ,count(pieces[1]),
为此:

print 'There were', count,

正如问题中的注释所提到的,count并不是作为函数列出的,而是一个int。您不能将片段[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

在脚本的顶部,您有count=0,这是不可调用的,即function/class/等。您希望它做什么?count是一个变量,而不是一个函数。我想,如果您只使用:print'There was',pieces[1],'lines in file with From作为第一个单词,它应该可以工作……正如其他答案所说:count不是一个函数,所以我不明白为什么您希望它工作。@Reti43我最初使用count=0来计算for循环中打印的每一行。但是我把那部分代码删掉了,因为它不是必需的。谢谢你向我指出这一点。我意识到这是不必要的代码。如果删除count=0,以后引用count时会出现名称错误。顺便说一下,您在输出中添加了额外的空格。已编辑。谢谢我已经有一段时间没有使用笨拙的print语句版本了……在python3中也会这样。默认分隔符是空格。非常感谢您帮助我解决了大部分问题。
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