以下是一个示例代码,用于标记连续的两行,其中第二行只包含一个日期:
import re
text = '''
Line 1: This is a sample text.
Line 2: 2021-01-01
Line 3: This is another sample text.
Line 4: 2021-01-02
Line 5: Yet another sample text.
'''
lines = text.split('\n')
for i in range(len(lines)-1):
if re.match(r'\d{4}-\d{2}-\d{2}', lines[i+1]):
print(f"Line {i+2} is a single date line: {lines[i+1]}")
print(f"Line {i+1} and Line {i+2} are consecutive lines.")
输出结果:
Line 2 is a single date line: 2021-01-01
Line 1 and Line 2 are consecutive lines.
Line 4 is a single date line: 2021-01-02
Line 3 and Line 4 are consecutive lines.
这个示例使用了正则表达式来匹配日期格式(YYYY-MM-DD)。在循环中,它通过检查下一行是否符合日期格式来确定是否存在一个单独的日期行。如果是这样,它将打印出这两行是连续行的信息。
下一篇:标记列