Search code examples
python-3.xfile-manipulation

How can I print the line index of a specific word in a text file?


I was trying to find a way to print the biggest word from a txt file, it's size and it's line index. I managed to get the first two done but can't quite figure it out how to print the line index. Can anyone help me?

def BiggestWord():
   list_words = []
   with open('song.txt', 'r') as infile:
       lines = infile.read().split()
       for i in lines:
          words = i.split()
          list_words.append(max(words, key=len))
   biggest_word = str(max(list_words, key=len))

   print biggest_word
   print len(biggest_words)

   FindWord(biggest_word)

def FindWord(biggest_word):

Solution

  • You don't need to do another loop through your list of largest words from each line. Every for-loop increases function time and complexity, and it's better to avoid unnecessary ones when possible.

    As one of the options, you can use Python's built-in function enumerate to get an index for each line from the list of lines, and instead of adding each line maximum to the list, you can compare it to the current max word.

    def get_largest_word():
        # Setting initial variable values
        current_max_word = ''
        current_max_word_length = 0
        current_max_word_line = None
    
        with open('song.txt', 'r') as infile:
            lines = infile.read().splitlines()
            for line_index, line in enumerate(lines):
                words = line.split()
                max_word_in_line = max(words, key=len)
                max_word_in_line_length = len(max_word_in_line)
                if max_word_in_line_length > current_max_word_length:
                    # updating the largest word value with a new maximum word
                    current_max_word = max_word_in_line
                    current_max_word_length = max_word_in_line_length
                    current_max_word_line = line_index + 1  # line number starting from 1
    
        print(current_max_word)
        print(current_max_word_length)
        print(current_max_word_line)
        return current_max_word, current_max_word_length, current_max_word_line
    

    P.S.: This function doesn't suggest what to do with the line maximum words of the same length, and which of them should be chosen as absolute max. You would need to adjust the code accordingly.

    P.P.S.: This example is in Python 3, so change the snippet to work in Python 2.7 if needed.