PYTHON
19
document py
Guest on 5th August 2022 02:58:00 PM
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A list representation of a document
Each line is represented as a list of words (strings).
The document consists of a list of such lines.
"""
def load_file(path):
"""
Returns the file at given path as a list-document.
@type path: string
@param path: a path to a text file
@return : a copy of an entity in the store
"""
file = open(path, 'r')
document = []
for row in file:
line = []
words = row.split()
for word in words:
line.append(word)
document.append(line)
return document
def find_lines(word, document):
"""
Returns the list of positions of all lines that contain the word.
@type word: string
@param word: the word searched for (exakt match)
@type document: list
@param document: the document to search in
@return : a list of positions (integers) of all lines that match
"""
lines = []
for line_no in xrange(len(document) - 1):
if word in document[line_no]:
lines.append(line_no)
return lines
# Test code
if __name__ == '__main__':
doc = load_file('my-doc.txt')
print doc
lines = find_lines("test", doc)
print lines