我正在开发一个chatterbot项目,该项目通过使用txt文件存储输入和输出来模仿用户。但我遇到了一个问题,它不能正确地比较文件的输入。
以下是代码行:
with open('memory.txt', 'r+') as mem:
#memory.txt is where is store the I/O. ex "(input)/(output)" helloinput/hellooutput
for line in mem.read():
#reiterates through each line
if(UI + '/') in line:
#Here is the problem, where the ui being the user input var is not comparing correct to the memory.txt file line.
#(yes) the / is needed for it to work and i have tried to str(UI + '/') but still no luck
print(line.rsplit('/',1)[0])
#this prints out everything after the / character
对不起,如果问题有点不清楚。
答案 0 :(得分:2)
mem.read()
将所有文件作为字符串整体读取
您需要使用mem.readlines()
。 readlines将文件读作行列表
或者你可以直接迭代文件指针
for x in mem: # here x is line
# do your stuff with line here