2016-03-14 21 views
0

我最近開始學習Python的,Python函數讀取文件和正則表達式

def bacafile(): 
    f=open('A157038027_S2TIB_2b.txt','r') 

    lines=f.read().split(',') 

    while lines!='': 
     lines=f.readline 
     for i in (len(f)): 
      temp (i)= open ('A157038027_S2TIB_2b.txt','r') 
      temp(i)=f 
      f=temp(i) 

      if (temp(i))==("[0-9]"): 
       print(temp(i),"integer number") 
      elif(temp(i))== ("([-+]?([0-9]*\.[0-9]+|[0-9]+"): 
       print(temp(i),"floating number") 
      elif (temp(i))== ("[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?"): 
       print (temp(i),"exponential number") 
      else: 
       print ("not number") 
    print(lines) 
    f.close() 

然而,在執行功能時,我收到錯誤,「不能指定函數調用」這是什麼意思是,我該如何解決它?

+0

這是當你說'溫(I)= ...'我不能說如何解決,雖然它,因爲我不知道你在努力完成什麼。 – zondo

回答

1

此代碼有幾個錯誤,但是您收到的錯誤消息來自temp(i)= ...等行。 temp(i)是函數調用的結果(您可以使用參數i調用函數temp),並且不能將該結果分配給任何內容。 a[i] = b是有效的(你指定了第i個元素),但是a(i) = b不是。

這裏有一些是錯誤的其他事情:

  • lines=f.readline:f.readline是一個函數,但沒有()你實際上並沒有調用該函數。
  • 您不需要readline的,因爲你已經看過你的第一個符合lines=f.read().split(',')
  • 語法錯誤的文件:你需要一個分號後def bacfile()

這裏是寫的那部分有更好的方式代碼:

def bacafile(): 
    with open('A157038027_S2TIB_2b.txt','r') as f: 
     for line in f: 
      # do something with the line 
      print line 
1

該錯誤告訴你到底是哪一行錯誤。第一個,我注意到,在你的代碼是這樣的:

temp (i)= open ('A157038027_S2TIB_2b.txt','r') 

此行說:

  1. 找到名爲temp
  2. 對象找到了一個對象名稱i
  3. 調用該對象(預計是函數或其他可調用對象)名爲temp傳入一個參數,它是由名字i
  4. 引用的對象分配給前述功能呼籲=操作者的右手側計算表達式的結果。
  5. (我就不解釋了右手邊,因爲我們已經達到了這個問題)

賦值的左邊必須是一個變量的名稱(或字段,或進入一個集合)。它不能是一個函數調用或其他任意表達式。

0

由於無論如何都給出了答案。讓我們從更一般的意義上談論改進您的代碼。

首先澄清:bakafile不是一個非常具有描述性的函數名稱。目標是KISS並能夠理解純粹基於標題的功能

此函數似乎試圖用十進制數字,帶或不帶指數的浮點數分析csv類文件,然後打印所有行。 parse_and_print可能會成爲一個好名字。

其次,分而治之。添加簡單的函數可以大大提高可讀性。

第三個魔術常數,文件名應該是一個參數或常量。

四,python推出了with關鍵字,簡化了io。

結果示例(什麼,我還以爲你在做解釋):

import re 

# compiling ahead of time improves performance, and allows you to 
# name what your regex does 
int_re = re.compile(r'^[-+]?[0-9]+$') 
float_re = re.compile(r'^[-+]?[0-9]*\.[0-9]+$') 
exp_re = re.compile(r'^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$') 

def is_int(string): 
    return int_re.search(string) != None 

def is_float(string): 
    return float_re.search(string) != None 

def is_exponent(string): 
    return exp_re.search(string) != None 

def parse(item): 
    if is_int(item): 
     print("integer number: %d" % int(item)) 
    elif is_float(item): 
     print("floating number: %.3f" % float(item)) 
    elif is_exponent(item): 
     print("exponential number: %e" % float(item)) 

def parse_and_print(filename): 
    with open(filename, 'r') as f: 
     # read all lines 
     for line in f: 
      for item in line.split(','): 
       item = item.strip()  # remove whitespace 
       parse(item)    # parse individual items 

     # reset the read position in the file to begin 
     f.seek(0) 

     # print all lines afterwards 
     for line in f: 
      print(line) 

parse_and_print('A157038027_S2TIB_2b.txt')