来自.txt的 Python 字符串输入和输出



im 正在处理一个 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

抱歉,如果问题似乎有点不清楚。

mem.read()将所有

文件作为一个字符串作为一个整体读取

您需要使用 mem.readlines() . readlines 将文件读取为行列表

或者可以直接遍历文件指针

for x in mem:             # here x is line
    # do your stuff with line here

相关内容

  • 没有找到相关文章

最新更新