[英]Python Error: TypeError: 'int' object is not callable
打開文件 mbox-short.txt 並逐行讀取。 當您找到以“From”開頭的行時,如下所示:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
您將使用 split() 解析 From 行並打印出該行中的第二個單詞(即發送消息的人的完整地址)。 然后在最后打印出一個計數。
提示:確保不要包含以“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
我不確定為什么我會得到這個 Traceback。
'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,
正如問題中的評論所提到的, 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.