Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'str' object is not callable (Python)

Tags:

python

Code:

import urllib2 as u import os as o inn = 'dword.txt' w = open(inn) z = w.readline() b = w.readline() c = w.readline() x = w.readline() m = w.readline() def Dict(Let, Mod):     global str     inn = 'dword.txt'     den = 'definitions.txt'      print 'reading definitions...'      dell =open(den, 'w')      print 'getting source code...'     f = u.urlopen('http://dictionary.reference.com/browse/' + Let)     a = f.read(800)      print 'writing source code to file...'     f = open("dic1.txt", "w")     f.write(a)     f.close()      j = open('defs.txt', 'w')      print 'finding definition is source code'     for line in open("dic1.txt"):         if '<meta name="description" content=' in line:            j.write(line)      j.close()      te = open('defs.txt', 'r').read().split()     sto = open('remove.txt', 'r').read().split()      print 'skimming down the definition...'     mar = []     for t in te:         if t.lower() in sto:             mar.append('')         else:              mar.append(t)     print mar     str = str(mar)     str = ''.join([ c for c in str if c not in (",", "'", '[', ']', '')])      defin = open(den, Mod)     defin.write(str)     defin.write('                 ')     defin.close()      print 'cleaning up...'     o.system('del dic1.txt')     o.system('del defs.txt') Dict(z, 'w') Dict(b, 'a') Dict(c, 'a') Dict(x, 'a') Dict(m, 'a') print 'all of the definitions are in definitions.txt' 

The first Dict(z, 'w') works and then the second time around it comes up with an error:

Traceback (most recent call last):   File "C:\Users\test.py", line 64, in <module>     Dict(b, 'a')   File "C:\Users\test.py", line 52, in Dict     str = str(mar) TypeError: 'str' object is not callable 

Does anyone know why this is?

@Greg Hewgill:

I've already tried that and I get the error:

Traceback (most recent call last):  File "C:\Users\test.py", line 63, in <module>     Dict(z, 'w')   File "C:\Users\test.py", line 53, in Dict    strr = ''.join([ c for c in str if c not in (",", "'", '[', ']', '')]) TypeError: 'type' object is not iterable 
like image 727
P'sao Avatar asked May 18 '11 03:05

P'sao


2 Answers

This is the problem:

global str  str = str(mar) 

You are redefining what str() means. str is the built-in Python name of the string type, and you don't want to change it.

Use a different name for the local variable, and remove the global statement.

like image 75
Greg Hewgill Avatar answered Oct 01 '22 18:10

Greg Hewgill


While not in your code, another hard-to-spot error is when the % character is missing in an attempt of string formatting:

"foo %s bar %s coffee"("blah","asdf") 

but it should be:

"foo %s bar %s coffee"%("blah","asdf") 

The missing % would result in the same TypeError: 'str' object is not callable.

like image 32
n611x007 Avatar answered Oct 01 '22 17:10

n611x007