How to compare the words in a text file with a list of keywords and run a funtion based on the keyword match?

809 views Asked by At

I have text file with this kind of data:

height 10.3
weight 221.0
speed 84.0 
height 4.2
height 10.1
speed 1.2

I want to read the file and each time I find one of the keywords height, weight, or speed I want to call a different function. For example, if I encounter the height keyword want to call the function convert_hight(h).

The keywords may appear in any order throughout the file, but they always appear at the beginning of the line.

I must point out that this is a simplified example, in reality I have hundreds of keywords and the text file may be quite large, so I want to avoid comparing each word in the file with each word in the keyword list.

How can I approach this problem? (I'm using python)

2

There are 2 answers

0
Ajax1234 On BEST ANSWER

You can use a dictionary of functions:

def convert_hight(h):
   #do something

def convert_speed(s):
   #do something

def convert_weight(w):
   #do something

d = {"height":convert_height, "weight":convert_weight, "speed":convert_speed}

data = [i.strip('\n').split() for i in open('filename.txt')]
for type, val in data:
   d[type](float(val))
0
Varad On

A slightly different implementation in python3

#!/usr/local/bin/python3


def htFn():
    return "Height"

def wtFn():
    return "Weight"

def readFile(fileName):
    """Read the file content and return keyWords."""
    KeyStrings = {
        'height': htFn(),
        'weight': wtFn(),
    }
    with open(fileName, "r") as configFH:
        for records in configFH.readlines():
            func = records.split()
            if func:
                print(KeyStrings.get(func[0]))


if __name__ == "__main__":
    readFile('lookup.txt')