【问题标题】:Read data from text file and use that data to get the dictionary data with python3从文本文件中读取数据并使用该数据通过 python3 获取字典数据
【发布时间】:2020-06-15 12:56:44
【问题描述】:

我对 python 语言比较陌生。我想从文本文件中读取数据(文本文件中的多行),然后使用从文本文件中读取的数据来执行字典函数。

def readCmd():
    f = open('cmd.txt', "r")
    line = f.readline()
    for line in f:

        print (line)
        time.sleep(1)
        return str(line)

    f.close()

def zero():
    print( "Hi 0")

def one():
    print( "Test 1")

def two():
    print( "end 2")

def num_to_func_to_str(argument):
    switcher = {
        "Hi": zero,
        "test": one,
        "end": two,
    }
    print(switcher.get(argument,"Please enter only 'Hi', 'test' and 'end'"))

def main():
    #readCmd()
    while 1 :
        time.sleep(0.5)
        num_to_func_to_str(readCmd())

if __name__ == "__main__":
    main()

上面的代码是我试过的代码。它只显示了第二行,而不是进入字典(切换器)条件。此代码跳至print(switcher.get(argument,"Please enter only 'Hi', 'test' and 'end'"))

文本文件中的数据如下。

start
Hi 
test
Hi 
test
Hi 
test
Hi 
test
Hi 
test
Hi 
test
end

谁能建议我如何解决这个问题? 谢谢

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    readCmd 在打开文件并在每次调用时读取第一行后返回。由于第一行是start,它与switcher 中的任何内容都不匹配。

    【讨论】:

    • 是的,就目前而言。我如何才能阅读文本文件?
    【解决方案2】:

    我刚刚解决了这个问题。我必须在文本文件中读取该数据并将该数据存储在列表类型中

    def zero():
        print ("called function 1")
    
    def one():
        print ("called function 2")
    
    def two():
        print ("called function 3")
    
    tokenDict = {
        "cat":zero,
        "dog":one,
        "bear":two
        }
    
    lineList = [line.rstrip('\n') for line in open("cmd.txt")]
    
    for line in lineList:
        time.sleep(1)
        # lookup the function to call for each line
        functionToCall = tokenDict[line]
        # and call it
        functionToCall()
    

    引用自[1]:http://code.activestate.com/recipes/65126-dictionary-of-methodsfunctions/ 参考自[2]:https://qiita.com/visualskyrim/items/1922429a07ca5f974467

    【讨论】:

    • 请注意,您没有必须这样做;你可以打开它一次,每次通过你的循环读取 1 行并处理它。
    猜你喜欢
    • 2012-08-06
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多