如何将文本文件中的单词与关键字列表和 运行 基于关键字匹配的函数进行比较?
How to compare the words in a text file with a list of keywords and run a funtion based on the keyword match?
我有包含这种数据的文本文件:
height 10.3
weight 221.0
speed 84.0
height 4.2
height 10.1
speed 1.2
我想读取文件,每次找到关键字 height
、weight
或 speed
之一时,我都想调用不同的函数。比如遇到height
关键字想调用函数convert_hight(h)
.
关键字可以在整个文件中以任意顺序出现,但它们始终出现在行的开头。
我必须指出这是一个简化的示例,实际上我有数百个关键字并且文本文件可能非常大,所以我想避免将文件中的每个词与关键字列表中的每个词进行比较.
我该如何解决这个问题?
(我正在使用 python)
您可以使用函数字典:
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))
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')
我有包含这种数据的文本文件:
height 10.3
weight 221.0
speed 84.0
height 4.2
height 10.1
speed 1.2
我想读取文件,每次找到关键字 height
、weight
或 speed
之一时,我都想调用不同的函数。比如遇到height
关键字想调用函数convert_hight(h)
.
关键字可以在整个文件中以任意顺序出现,但它们始终出现在行的开头。
我必须指出这是一个简化的示例,实际上我有数百个关键字并且文本文件可能非常大,所以我想避免将文件中的每个词与关键字列表中的每个词进行比较.
我该如何解决这个问题? (我正在使用 python)
您可以使用函数字典:
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))
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')