类型错误:“str"对象不可调用(Python) [英] TypeError: 'str' object is not callable (Python)

查看:80
本文介绍了类型错误:“str"对象不可调用(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') 工作,然后第二次出现错误:

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:

@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

推荐答案

这是问题所在:

global str

str = str(mar)

您正在重新定义 str() 的含义.str 是字符串类型的内置 Python 名称,您不想更改它.

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.

为局部变量使用不同的名称,并删除 global 语句.

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

这篇关于类型错误:“str"对象不可调用(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆