# -*- coding: utf-8 -*-
"""pos_replace.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1Mdfqrn2Nc8xE6xFlAstCmzPeEMCgguP-
"""

import nltk
from nltk import word_tokenize, pos_tag
import pandas as pd
import io

try:
  nltk.data.find('tokenizers/punkt')
except LookupError:
  nltk.download('punkt')

try:
  nltk.data.find('taggers/averaged_perceptron_tagger')
except LookupError:
  nltk.download('averaged_perceptron_tagger')

try:
  nltk.data.find('taggers/universal_tagset')
except LookupError:
  nltk.download('universal_tagset')

template = pd.read_csv('/content/replace_template.csv')

template=template.fillna('')

text1 = "the warmer areas i am at your bb was he who does that is"

text2 = "at your bb from your obey for you will be"

def pos_replace(l,template):
  l_r = l
  for i in range(len(template)):
    row = template.iloc[i]
    pos_before = str(row['pos_before']).split(';')
    pos_after = str(row['pos_after']).split(';')
    replace_list = str(row['replace']).split(';')
    for p in replace_list:
      if p in l_r:
        y = p.replace(' ','')
        interim = l_r.replace(p, y)
        words = word_tokenize(interim)
        interim_pos = pos_tag(words, tagset='universal')
        index_=[i for i,x in enumerate(interim_pos) if x[0]==y]
        for i in index_:
          if interim_pos[i-1][1] in pos_before:
            print('the pos of the word before', p, 'is',interim_pos[i-1][1])
            words[i] = row[0]
            # l_r=l_r.replace(p, row[0])
            l_r = " ".join(words)
            print(l_r)
          elif interim_pos[i+1][1] in pos_after:
            print('the pos of the word after', p, 'is',interim_pos[i+1][1])
            words[i] = row[0]
            # l_r=l_r.replace(p, row[0])
            l_r = " ".join(words)
            print(l_r)
  return l_r

pos_replace(text1,template)

pos_replace(text2,template)