How to skip a empty line in text file using python

后端 未结 4 1514
一生所求
一生所求 2021-01-29 08:51

I have a text file as below.

  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| de         


        
相关标签:
4条回答
  • 2021-01-29 09:19

    You can count the size of words:

    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'")
    

    The output:

    4th word is 'book' or 'pencil'
    4th word is 'book' or 'pencil'
    4th word is 'pen'
    
    0 讨论(0)
  • 2021-01-29 09:28

    When using for l in fr python doesn't return an array but a string for each line, that you have to process in the loop. Using l.strip().split() will give you an array of strings, where a string would equal a word.

    Then, is is meant to compare object type, like is this line a string ? or an int ?. So you cannot use it here. Use == to compare two objects of the same type.

    Edit: some example code

    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()
    
    0 讨论(0)
  • 2021-01-29 09:28

    You can verify the list length at the beginning of your for loop and then continue if there is no 3rd element:

    if len(l)< 3: continue

    PS. Of course, you have to l.split() the line first, otherwise you will access single characters only.

    0 讨论(0)
  • 2021-01-29 09:42

    You can check the length of the array of words.

    But do note, when you index directly on l, you are going at the character level and not the word level as you seem to want to. Also, I'd use == instead of is.

    Do something like this:

    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")
    
    0 讨论(0)
提交回复
热议问题