# wget http://cs.whitman.edu/~davisj/cs/167/2016F/exmpls/analyzing-text.py
# All code from Havill's (2016) _Discovering Computer Science_, section 6.5

def count(text, target):
  """Count the number of target strings in text.

  Parameters:
    text: A string object to search in
    target: A string object to search for

  Return value: the number of occurrences of target in text
  """

  count = 0
  for index in range(len(text)):
    if text[index:index + len(target)] == target:
      count += 1
  return count

def find(text, target):
  """Find the first occurrence of target in text.

  Parameters:
    text: A string object to search in
    target: A string object to search for

  Return value: The index of the first occurrence of target in text
  """
  
  for index in range(len(text) - len(target) + 1):
    if text[index:index + len(target)] == target:
      return index
  return -1

def concordanceEntry(filename, word):
  """Print all lines in a text file containing the given word.

  Parameters:
    filename: the name of the text file as a string
    word: the word to search for

  Return value: none
  """

  textfile = open(filename, 'r', encoding='utf-8')
  linecount = 1
  for line in textfile:
    found = find(line, word)
    if found >= 0:
      space = ' ' * (80 - len(word) - found)
      print('{0:<6}'.format(linecount) + space + line.rstrip())
    linecount += 1
  textfile.close()
