【问题标题】:How to compare the words in a text file with a list of keywords and run a funtion based on the keyword match?如何将文本文件中的单词与关键字列表进行比较并根据关键字匹配运行函数?
【发布时间】:2017-09-07 14:07:40
【问题描述】:

我有包含此类数据的文本文件:

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

我想读取文件,每次找到关键字heightweightspeed 之一时,我都想调用不同的函数。比如我遇到height关键字想调用函数convert_hight(h)

关键字可以在整个文件中以任意顺序出现,但它们始终出现在行首。

我必须指出,这是一个简化的例子,实际上我有数百个关键字并且文本文件可能非常大,所以我想避免将文件中的每个单词与关键字列表中的每个单词进行比较。

我该如何解决这个问题? (我用的是python)

【问题讨论】:

    标签: python python-3.x text-files keyword-search


    【解决方案1】:

    您可以使用函数字典:

    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))
    

    【讨论】:

      【解决方案2】:

      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')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 2012-06-07
        • 1970-01-01
        • 1970-01-01
        • 2017-06-21
        • 2020-11-19
        相关资源
        最近更新 更多