2014-02-16 103 views
0

如果一行中有多個整數,如何將該行轉換爲整數。 (在完成行可能是「2 4」和完成= int(行)的原因和錯誤。從Python中的文件中讀取int時出錯

另外,我怎樣才能訪問特定元素的轉換在for循環底部。名單,但我需要比較特定元素

with open(r'C:\Users\Andrew\Documents\College\Theory of Computation\dfa19btest.txt', 'r') as f: 
    for i, line in enumerate(f): 
    if i == 0: 
     language = line 
     print("Language =", language) 
    if i == 1: 
     numstates = int(line) 
     print ("Number of states =", numstates) 
    if i == 2: 
     start = int(line) 
     print ("Start =", start) 
    #if i == 3: 
     #finish = int(line) 
     #print ("Finish =", finish) 
    if i >= 4: 
     transitions.append(line) 
     print ("Transitions = ", transitions[i -4]) 

for x in range(numstates-1, -1, -1): 
    print(transitions[x]) 
    # string is in 4 a 2 b 3 format 
    # if [0] == [3] then answer insert [2]* into answer array 
    # if [2] and [4] are followed by same number insert [2]|[4] 
+0

應該只是'numstates = int(numstates)',但在兩個for循環中使用'i'是危險的:你不一定需要枚舉(使用'f.next()') – colcarroll

回答

0

來解析字符串爲整數使用:int

的爲例:

str_var = '123' 
int_var = int(str_var) # int_var now have the interger value 123 
0

您需要如果您的任何輸入無效,即非整數,則決定應該發生什麼。以下是Python2的簡化示例。注意try/except子句。

with open(r'C:\Users\Andrew\Documents\College\Theory of Computation\dfa19btest.txt', 'r') as f: 
    for i, line in enumerate(f): 
     if i == 0: 
      language = line 
      print("Language =", language) 
     try: 
      if i == 1: 
       numstates = int(line) 
       transitions = np.array(numstates) 
       print ("Number of states =", numstates) 
      if i == 2: 
       start = int(line) 
       print ("Start =", start) 
      if i == 3: 
       finish = int(line) 
       print ("Finish =", finish) 
     except ValueError: 
      print "Invalid int (%s) on line: %d" % (line, i) # use print() for Python3 
      break 
+0

如果一行中有多個整數,還有其他需要的東西。在行結束時,該行讀取「2 4」並出現錯誤。 – adod

+0

這是從原來的問題,這意味着只有一個整數每行讀取的變化。如果有多個整數,你想要做什麼? –

+0

是的,對不起,我忘記了完成可能有多個州。這應該將NFA轉換爲正則表達式。我認爲把它作爲一個字符串是可行的,我可以將它的元素與轉換的元素進行比較。 – adod