PYTHON   19

document py

Guest on 5th August 2022 02:58:00 PM

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. """
  5. A list representation of a document
  6.  
  7. Each line is represented as a list of words (strings).
  8. The document consists of a list of such lines.
  9. """
  10.  
  11. def load_file(path):
  12.     """
  13.    Returns the file at given path as a list-document.
  14.  
  15.    @type  path: string
  16.    @param path: a path to a text file
  17.  
  18.    @return  : a copy of an entity in the store
  19.    """
  20.     file = open(path, 'r')
  21.     document = []
  22.     for row in file:
  23.         line = []
  24.         words = row.split()
  25.         for word in words:
  26.             line.append(word)
  27.         document.append(line)
  28.     return document
  29.  
  30. def find_lines(word, document):
  31.     """
  32.    Returns the list of positions of all lines that contain the word.
  33.  
  34.    @type  word: string
  35.    @param word: the word searched for (exakt match)
  36.    @type  document: list
  37.    @param document: the document to search in
  38.  
  39.    @return  : a list of positions (integers) of all lines that match
  40.    """    
  41.     lines = []
  42.     for line_no in xrange(len(document) - 1):
  43.         if word in document[line_no]:
  44.             lines.append(line_no)
  45.     return lines
  46.            
  47. # Test code
  48. if __name__ == '__main__':    
  49.     doc = load_file('my-doc.txt')
  50.     print doc
  51.     lines = find_lines("test", doc)
  52.     print lines

Raw Paste


Login or Register to edit or fork this paste. It's free.