首页 > 解决方案 > 如何索引列表中的一行

问题描述

我有一个从文本文件导入的列表,我试图迭代并检查 for 循环中的每一行(行)。

现在我卡在一个点,我需要读取下一行才能采取行动,我试图将其更改为 Pandas 数据框,这不太方便。

这是我的数据的示例,它是我从中读取的文本文件

Hello all my name is :
I am 30 years old
if i said hi : print hello
ELSE 
dont

这是我的代码:

with open('source.txt') as f:
    lines = f.readlines()

for line in lines:
if 'name' in line:
print('Name was mentioned')
elif 'age' in line :
 print('Age was mentioned')
elif 'hi' in line and 'ELSE' in line( *HERE i want to read the next line*)

有任何想法吗?

谢谢

标签: pythontext

解决方案


with open('source.txt') as f:
    lines = f.readlines()
    for index, line in enumerate(lines):
        try:
            next_line = lines[index + 1] # try to access next.
        except IndexError:
            next_line = None # if no next row, set next_line to None

        print(line)
        print(next_line)

推荐阅读