python - 如何索引列表中的一行
问题描述
我有一个从文本文件导入的列表,我试图迭代并检查 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*)
有任何想法吗?
谢谢
解决方案
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)
推荐阅读
- php - Codeigniter .htaccess 重定向网址问题
- android - Android:“id 没有在任何地方定义”,但它显然是
- html - 如何转一个
- python - 任何人都可以帮助我进行python网络抓取,下面是代码
- python - 如何在 Matplotlib 中指定绘图的顺序?
- oracle - SQLPLUS:在后台打印到文件时停止终端输出
- mysql - 如何在 Laravel 中编写原始查询
- javascript - 如何将 JSON 数据保存到 JavaScript 中的变量
- django - 如何通过 Get_context_data 获取 ListView 中每篇博文的评论数?通过 self.id/self.object.id/self 过滤不起作用
- sql-server - SQL Server 2017 Ubuntu Ole 自动化程序