一尘不染

TypeError:'str'对象不可调用(Python)

python

码:

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'

第一次Dict(z, 'w')工作,然后第二次出现错误:

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

有人知道为什么是这样吗?

我已经尝试过了,但出现错误:

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

阅读 619

收藏
2020-02-20

共2个答案

一尘不染

这就是问题:

global str

str = str(mar)

你正在重新定义什么str()意思。str是字符串类型的内置Python名称,你不想更改它。

为本地变量使用其他名称,然后删除该global语句。

2020-02-20
一尘不染

虽然不在你的代码中,但是另一个难以发现的错误是当%尝试格式化字符串时缺少字符时:

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

但是应该是:

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

丢失%将导致相同的结果TypeError: 'str' object is not callable。

2020-02-20