# Additional examples of text files processing

# A list of topics is given in a file,
# each topic occupies one line.
# Print the topics with some particular properties

def extractLinesWithWord( fileName, givenWord):
    file = open( fileName, "r" )
    text = file.read().splitlines() # list of strings

    '''
    text = file.read()
    print(text)

    Ltext = list(text) # string --> list of its characters
    print( Ltext)

    text = text.replace( "\n" , "[______]")
    print( text)

    #print(text)
    #Ltext = list(text)
    #print(Ltext)
    '''
    resultList = []
    for line in text:
        words = line.split() # ["3D", "triangle",  "intersection"]
        if givenWord in words:
            resultList.append(line)
    file.close()
    return resultList


# what if the given word is just a part of some other word like a.g.
# "meter" is  a part of "diameters".

def extractLinesWithWord2( fileName, givenWord, wholeWord ):
    file = open( fileName, "r" )
    text = file.read().splitlines() # list of strings

    resultList = []
    for line in text:
        words = line.split()
        for wordItem in words:    # ["3D", "triangle",  "intersection"]
            if wholeWord == True:
                if wordItem == givenWord:   #"tree"
                    resultList.append(line)
                    # is the following break necessary?
                    break # do not search any more
            if wholeWord == False:
                if wordItem.find(givenWord) >= 0:
                    resultList.append(line)
                    break # ditto (= same as said before)
    file.close()
    return resultList

def extractLinesWithBrackets( fileName ):
    file = open( fileName, "r" )
    text = file.read().splitlines() # list of strings
    resultList = []
    char1 = "("
    char2 = ")"

    for line in text:
        posChar1 = line.find(char1)
        posChar2 = line.find(char2)
        # KISS strategy == "Keep It Small and Stupid"
        if posChar1 >= 0 and posChar2 >= 0 and posChar1 < posChar2:
            resultList.append(line)

    file.close()
    return resultList




# ---------------------------------------------------------------------------
#             M A I N
# ---------------------------------------------------------------------------

# Define your own path to the data on your disk:
path ="d:\\Iskola\\PGE2020\\data\\"
fname = "topicsAll.txt"
#fname = "topicsPart.txt"
givenWord = "meter"
givenWord = "tree"

#resList = extractLinesWithWord(path+fname, givenWord)
#for i in range(len(resList)):
#    print(str(i+1)+". "+resList[i])

#print("-"*40)

resList = extractLinesWithWord2(path+fname, givenWord, False )
for i in range(len(resList)):
    print(str(i+1)+". "+resList[i])

print("-"*40)

resList = extractLinesWithBrackets(path+fname )
for i in range(len(resList)):
    print(str(i+1)+". "+resList[i])


