0

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

  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

谢谢你!(我知道我进口了一堆我不需要的东西。请不要提及。)

4

1 回答 1

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
于 2016-01-25T17:43:36.587 回答