2017-09-07 18 views
1

私はこの種のデータのテキストファイルがあります:私は、ファイルと私は別の関数を呼び出すしたいキーワードheightの1、weight、またはspeedを見つけるたびに、読みたいテキストファイルの単語とキーワードのリストを比較して、キーワードの一致に基づいてfuntionを実行するにはどうすればよいですか?

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

を。たとえば、heightキーワードが発生した場合は、convert_hight(h)という関数を呼び出します。

キーワードはファイル内のどの順序でも表示されますが、常に行の先頭に表示されます。

これは単純な例であり、実際には何百ものキーワードがあり、テキストファイルがかなり大きい可能性がありますので、ファイル内の各単語とキーワードリストの各単語を比較しないようにします。

どうすればこの問題に近づくことができますか?あなたが関数の辞書を使用することができます

答えて

2

(私が使用しているのpython):のpython3で

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

A若干異なる実装を

#!/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') 
関連する問題