python - Python:提取文本文件中两个字符串之间的值
问题描述
我有一个这样的对话文本文件:
Mom:
Hi
Dad:
Hi
Mom:
Bye
Dad:
Bye
Dad:
:)
我必须将两个扬声器行复制到它们自己的文本文件(mom.txt 和 dad.txt)这可行,但问题是如果连续有两行或多行相同的扬声器。
def sort(path):
inFile= open(path, 'r')
inFile1= open(path, 'r')
copy = False
outFile = open('mom.txt', 'w')
outFile1 = open('dad.txt', 'w')
keepCurrentSet = False
for line in inFile:
if line.startswith("Dad:"):
keepCurrentSet = False
if keepCurrentSet:
outFile.write(line)
if line.startswith("Mom:"):
keepCurrentSet = True
for line1 in inFile1:
if line1.startswith("Mom:"):
keepCurrentSet = False
if keepCurrentSet:
outFile1.write(line1)
if line1.startswith("Dad:"):
keepCurrentSet = True
outFile.close()
outFile1.close()
inFile1.close()
outFile1 结果如下所示:
Hi
Bye
Dad:
:)
应该看起来像:
Hi
Bye
:)
想法或更简单的方法来做到这一点?谢谢
解决方案
这是您可以在一个循环中编写mom.txt
的一种方法:dad.txt
def sort(path):
inFile= open(path, 'r')
inFile1= open(path, 'r')
copy = False
outFile = open('mom.txt', 'w')
outFile1 = open('dad.txt', 'w')
keepCurrentSetDad = False
keepCurrentSetMom = False
for line in inFile:
print("--->",line)
if 'Dad' in line:
keepCurrentSetDad = True
keepCurrentSetMom = False
continue
elif 'Mom' in line:
keepCurrentSetMom = True
keepCurrentSetDad = False
continue
if keepCurrentSetDad:
outFile1.write(line)
elif keepCurrentSetMom:
outFile.write(line)
outFile.close()
outFile1.close()
inFile1.close()
我只是编辑了你的代码。请检查您的 txt 文件。无论你在这里展示什么,说话者都在一行,说话者的话在下一行。我一直坚持这种格式。
推荐阅读
- django - Crispy 表单抛出 VariableDoesNotExist 错误,在表单上查找键 [html5_required] 失败
- node.js - 在 NodeJs 中使用配置模块返回“未定义”
- mongodb - Mongoose 开关集合动态类似于使用 useDb 的数据库
- c++ - 如何为曲线设置名称?
- node.js - 2条完全相同的路线中的1条的Mongoose/Express CastError?
- opengl - 是什么导致基于状态的顶点着色器的 GLSL 重新编译?
- java - Spring中异步发送消息中的“主题”一词是什么意思?
- undefined - 如何使用 React Google Maps 让我的路线显示在我的地图上?
- amazon-web-services - 胶水 ETL 脚本加载每日文件不起作用
- c# - C# 中的 Google 身份工具包 API