【问题标题】:TypeError: coercing to Unicode: need string or buffer, file found?TypeError:强制转换为 Unicode:需要字符串或缓冲区,找到文件?
【发布时间】:2016-05-02 02:41:00
【问题描述】:

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

  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

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

【问题讨论】:

  • 你解决了吗?如果我的回答有帮助,我们将不胜感激。

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


【解决方案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

【讨论】:

  • 我以为我使用 talk.close() 关闭了文件?
  • 它可能是一个关闭的文件句柄,但它仍然是一个文件句柄而不是一个字符串。我建议不要为您的文件名和文件句柄使用相同的变量。很难给你一个例子,因为我不确定你想用你的代码来完成什么。您从用户那里获得输入,然后将该输入用作文件名(潜在的安全问题)。您还打开一个文件进行读取,但从不从中读取。如果您在打开文件时遇到异常,您会尝试再次打开它并从中读取(这几乎肯定会失败)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-28
  • 2015-02-01
  • 2014-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多