简体   繁体   English

从文本文件中读取数据并使用该数据通过 python3 获取字典数据

[英]Read data from text file and use that data to get the dictionary data with python3

I am newer for a python language.我是 python 语言的新人。 I want to be read the data from the text file(multiple lines in the text file), Then use the data that read from the text file to execute with the dictionary function.我想从文本文件中读取数据(文本文件中的多行),然后使用从文本文件中读取的数据与字典 function 一起执行。

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

The above code is the code that I tried.上面的代码是我试过的代码。 it showed just the second line and not go to the dictionary(switcher) condition.它仅显示第二行而不是 go 到字典(切换器)条件。 This code is skipped to print(switcher.get(argument,"Please enter only 'Hi', 'test' and 'end'"))这段代码跳到print(switcher.get(argument,"Please enter only 'Hi', 'test' and 'end'"))

The data in text file as below.文本文件中的数据如下。

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

Can anyone suggest to me for the how to solve this?谁能建议我如何解决这个问题? thanks谢谢

readCmd returns after opening the file & reading the first line every time it is called. readCmd在打开文件并在每次调用时读取第一行后返回。 Since that first line is start , it doesn't match anything in switcher .由于第一行是start ,它与switcher中的任何内容都不匹配。

I just resolved this issue.我刚刚解决了这个问题。 I have to read that data in a text file and store that data in the list type我必须在文本文件中读取该数据并将该数据存储在列表类型中

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM