从文本文件为确定性有限自动机创建Python字典

2024-06-03 05:20:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python创建一个程序,实现自动机显示的功能。自动装置的工作原理如图所示

enter image description here

我想让程序为我想要的每一台自动机工作。因此,我有一个dfa.txt来描述给定的自动机

dfa.txt

3       //Number of states of the DFA
0 1     //Accepted characters
0       //initial state
0 1     //final state
0 1 1   //If the automaton is in state q0 and reads 1 it goes to state q1 
0 0 0   //If the automaton is in state q0 and reads 0 it goes to state q0
1 1 2   //If the automaton is in state q1 and reads 1 it goes to state q2
1 0 0   //If the automaton is in state q1 and reads 0 it goes to state q0
2 1 2   //If the automaton is in state q2 and reads 1 it goes to state q2
2 0 2   //If the automaton is in state q2 and reads 0 it goes to state q2

我面临的问题是,我无法将它转换成一个像自动机所显示的那样正常工作的词典。我知道我可以在dfa.py类型的文件中创建字典,但该程序必须适用于文本文件。我应该如何将其转换成字典并使其在我的代码中工作

这就是我目前所拥有的

n = 'y'
def readFile(): #function that is intended to create a dictionary from the text file
    dictionary = {}
    with open('dfa.txt', 'r') as dict:
            for line in dict:
                    a,b,c = line.split()    #line split
                    dictionary[a] = int(b)  #matching the first column of the text file with the wanted transisions 
                    dictionary[a] = int(c)  #matching the first column of the text file with the wanted transisions 
            return dictionary
while n != 'n':                 #loop  for multiple checks
    s = input('\n' + 'Enter the string: ')

    def accepts(transitions,initial,accept,accepting,s):    #(transisions from dictionary,initial state, final state, final state, string) 
            state = initial
            for c in s:                                 #checking all the possible transisions for the inputed string from the dictionary
                    state = transitions[state][c]
            if(state in accept or state in accepting):  #if the transisions end in a accepted from the dictionary final state prints True
                    print (True)
            else:
                    print (False)
#accepts(dictionary,0,{4},{5},s)            #Excecution

    n = input('\n' + 'Do you want to enter a new string?(y/n): ')   #Option for new input

Tags: andthetoinfordictionaryifis