【问题标题】:How to skip a empty line in text file using python如何使用python跳过文本文件中的空行
【发布时间】:2017-05-21 09:17:20
【问题描述】:

我有一个如下的文本文件。

  l[0]l[1]l[2]l[3]l[4]l[5]l[6]
-----------------------------------
1| abc is a book and cba too
2| xyz is a pencil and zyx too
3| def is a pen and fed too
4| aaa is

实际文件是:

 abc is a book and cba too
 xyz is a pencil and zyx too
 def is a pen and fed too
 aaa is

我正在使用下面的代码对该文本文件执行操作:

import sys
fr = open("example.txt",'r')
for l in fr:
     if(l[3] is "book" or l[3] is "pencil")
          Then do something
     if(l([3] is "pen")
           Then do something
fr.close()

当我尝试执行这个程序时,我遇到了类似的错误

Traceback(most recent call last):
File "abc.py" line 4 in <module>
if(l[3] is "book" or l[3] is "pencil"):
IndexError: list index error out of range

因为根据上述文本文件的最后一行(即第 4 行),l[3] 处没有任何内容

l[0] l[1] l[2] l[3] l[4] l[5] l[6]
aaa是

这里的第 4 行 l[3] 是空的。 所以我的问题是当 l[3] 为空时如何跳过这一行? 我们可以像下面这样露营吗

if(l[3] ==""):
     continue

请有人在这里帮助我。

【问题讨论】:

  • 请格式化您的问题,以便我们尝试了解您的问题。

标签: python python-2.7 python-3.x


【解决方案1】:

您可以检查单词数组的长度。

但是请注意,当您直接在 l 上建立索引时,您将进入字符级别,而不是您想要的单词级别。另外,我会使用== 而不是is

做这样的事情:

with open("a.txt", 'r') as fr:
    for l in fr:
        words = l.split()
        if len(words) < 3:
            continue
        if words[3] == "book" or words[3] == "pencil":
            print("Book or pencil")
        elif words[3] == "pen":
            print("Pen")

【讨论】:

    【解决方案2】:

    当使用for l in fr 时,python 不会返回一个数组,而是为每一行返回一个字符串,您必须在循环中进行处理。使用l.strip().split() 会给你一个字符串数组,其中一个字符串等于一个单词。

    然后,is 用于比较对象类型,例如 is this line a string ? or an int ?。所以你不能在这里使用它。使用== 比较两个相同类型的对象。

    编辑:一些示例代码

    import sys
    fr = open("example.txt",'r')
    
    for l in fr:
        word = l.strip().split()
        if word[3] == "book" or word[3] == "pencil":
            # Do something
        elif word[3] == "pen":
            # Do something
    
    fr.close()
    

    【讨论】:

    • 非常感谢 Taz8do29 :)
    【解决方案3】:

    如果没有第三个元素,您可以在 for 循环的开头验证列表长度,然后验证 continue

    if len(l)< 3: continue

    PS。当然,你必须先l.split()这一行,否则你只能访问单个字符。

    【讨论】:

      【解决方案4】:

      你可以数单词的大小:

      with open("example.txt", 'r') as example_file:
          for line in example_file:
              words = line.strip().split()
              if len(words) > 3:  # line has more than three words
                  if words[3] in ['book', 'pencil']:
                      print("4th word is 'book' or 'pencil'")
                  elif words[3] == 'pen':
                      print("4th word is 'pen'")
      

      输出:

      4th word is 'book' or 'pencil'
      4th word is 'book' or 'pencil'
      4th word is 'pen'
      

      【讨论】:

      • @jsbueno 谢谢,我改进了 sn-p。
      • 非常感谢大流士 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多