python - 如何忽略缺失数据的行

标签 python

我有一个巨大的文件,其中有 0-10 行制表符分隔。我的问题是,如何忽略缺少空行 [4] 的整行?我的输入文件,

1 GRMZM2G052619_P03 10 56       a b c d e y        
2 GRMZM5G888620_P01 23 67 go:89 f g h k l m     
3 GRMZM5G886789_P02 45 89       o p r s t w

所以,我的最终输出应该是这样的,

2 GRMZM5G888620_P01 23 67 go:89 f g h k l m

import re
f=open('input.txt','r') 
r=open('output.txt','w')
lines=f.readlines() 
for line in lines:
   new_list=re.split(r'\t+',line)
   go_acc=new_list[4]
   if go_acc != '':
       r.writelines(line)
f.close()
r.close() 

我认为这一行有问题 if go_acc != '':

最佳答案

这里的问题是,由于您通过正则表达式 \t+ 分割该行,因此生成的字符串列表将不包含任何空字符串 - 这些“空”字段将只是跳过了。例如,第一行将被解析为 ["1", "GRMZM2G052619_P03", "10", "56", "a", "b", "c", "d", "e", "y"],因此索引 4 处的项目不是 '' 而是 "a"

我认为在这种情况下更好的方法是实际尝试匹配您正在寻找的内容。例如,如果索引 4 处的可选内容是 go:XX,其中 XX 是某个数字,那么您可以执行以下操作:

import re

f=open('input.txt','r') 
r=open('output.txt','w')

for line in f.readlines():
    if re.search(r'go:\d+', line):
        r.write(line + "\n")

f.close()
r.close() 

关于python - 如何忽略缺失数据的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23392391/

相关文章:

python - 在Paramiko中执行curl时,其输出在stderr中,而不是stdout中

python - (在 OpenCV 中将 .mat 文件作为图像加载)- 将具有 128 个 channel 的 numpy 数组 reshape 为 3 个 channel

Python 电子邮件 - 使用冒号导致无输出

Python 将立体声 .flac 转换为单声道

python - 这个简单的密码算法是否足够强大?

python - 为什么 Python 的 @staticmethods 与装饰类的交互如此糟糕?

python - Python 上的 Gurobi 优化器

python - 无法导入 flup.server.fcgi

python - 为什么 print(0.3) 打印 0.3 而不是 0.30000000000000004

Python多处理大量数据