TypeError:强制转换为Unicode:需要字符串或缓冲区,找到文件?

时间:2016-01-25 17:25:18

标签: python python-2.7 artificial-intelligence typeerror chatbot

我遇到了一个简单的聊天机器人的早期原型问题,它将使用它必须添加到以后可以使用的响应数据库的对话。

  import sys,time,random, os.path

typing_speed = 50 #wpm
def slow_type(t):
    for l in t:
        sys.stdout.write(l)
        sys.stdout.flush()
        time.sleep(random.random()*10.0/typing_speed)
    print ''

slow_type("Hello! My name is TUTAI, or Turing Test Artificial Intelligance")

slow_type("Currently I am in training, so my features arent fully complete.")

slow_type("If you say something I don't understand yet, I will repeat it back to you in order for me to learn and build a databace of responces!")

talk = raw_input()

talk = talk + ".txt"

existance = True

try:
    talk = open(talk, "r")

except:
    existance = False
    talk.close()

if existance == True:
    talkBack = open(talk, "r")
    print talkBack.read()

然而,当我运行程序时,我收到了这个回复(是的,我检查过文件是否存在)。

Hello! My name is TUTAI, or Turing Test Artificial Intelligence
Currently I am in training, so my features aren't fully complete.
If you say something I don't understand yet, I will repeat it back to you in order for me to learn and build a database of responses!
(I type)Hello

Traceback (most recent call last):
  File "H:\TUTAI\firstPythonScript.py", line 31, in <module>
    talkBack = open(talk, "r")
TypeError: coercing to Unicode: need string or buffer, file found

谢谢! (我知道我输入了一些我不需要的东西。请不要提及。)

1 个答案:

答案 0 :(得分:1)

我的猜测是,在程序中的那一点,'talk'变量是一个文件句柄,而不是一个字符串。我会劝阻这里看到的变量重复使用,因为它会导致你遇到的问题。

您的代码进展:

talk = raw_input() #string
talk = talk + '.txt' #string
talk = open(talk, 'r') #file handle
talkBack = open(talk, "r") #error, talk is still file handle