python - 我想从 .txt 文件中读取多行
问题描述
我想从.txt
文件中读取多行。每行代表一个将由 NLTK Python 脚本回答的问题,然后答案将写入另一个 .txt 文件。我成功地使这种机制起作用,但仅适用于 Question.txt 文件(提取问题的文件)中的一行(一个问题)。
正如我看到的场景,我想从 Question.txt 文件中读取一行,然后脚本将回答并将答案写入 Answer.txt 文件中。然后将从 Question.txt 文件中读取第二行,依此类推。
myFile = open("Questions.txt", 'r')
user_response=str(myFile.splitlines()) # Convert the content of the txt file from list format to string format in order to be able to lower the characters later
#I also made this little implementation in order for the code not to run infinitely, so to count the number of lines :
numOfLines = len(user_response.splitlines())
numofLines -= 1
解决方案
在python中,文件是迭代器,所以为了避免内存中存储大数组,你的简单解决方案是:
with open("Questions.txt") as q_f, open("Answers.txt", 'w') as a_f:
for question in q_f:
answer = solve(question)
a_f.write(answer+"\n")
在这里,您逐行迭代文件,回答问题并将其保存在另一个文件中,而无需将大列表保存在内存中
推荐阅读
- php - Vue Axios 不保存在 Laravel 控制器中
- unity3d - 将 Unity 2d 动画导出为 spritesheet
- json - 从使用 python 读取 JSON 文件中选择随机问候语
- command-line - 使用命令行向其他团队用户发送文件
- reactjs - 未定义不是反应原生的对象(评估'global.navigator.userAgent.match)
- javascript - JS函数不起作用
- javascript - 使用“google-libphonenumber”中的 PhoneNumberFormat 不起作用
- excel - 根据单元格数据调整形状大小
- php - 在 php 中处理时显示结果
- javascript - 使用纯 JS 将表转换为键值对