2 回答
TA贡献1827条经验 获得超4个赞
正则表达式替换可以处理这个:
import re
text = """A:
I can not believe the weather today .
B:
It is beautiful outside ."""
text = re.sub(r"^(\w+:)\s*", r"\1 ", text, flags=re.MULTILINE)
print(text)
# A: I can not believe the weather today .
# B: It is beautiful outside .
编辑:
基于更新的问题,对于多线对话:
import re
text = """A:
Well hello .
Long time no see .
How are you doing ?
B:
Good .
How are you ?"""
text = re.sub(r"(.*?)\s*\n(?!\w+:)", r"\1 ", text, flags=re.MULTILINE)
print(text)
# A: Well hello . Long time no see . How are you doing ?
# B: Good . How are you ?
TA贡献1851条经验 获得超4个赞
如果短语在一行上,这应该有效:
lines = file.readlines()
for ii in range(1,len(lines),2):
print(lines[ii-1][:-1]+lines[ii])
添加回答
举报