afif badawi
afif badawi

Reputation: 1

python function to read file and regular expression

I have recently started learning 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()

However, when the function is executed, I receive the error, "Can't assign to function call" What does this mean, and how do I fix it?

Upvotes: 0

Views: 67

Answers (3)

Work of Artiz
Work of Artiz

Reputation: 1090

Since the answer has been given anyway. Let's talk about the improving your code in a more general sense.

First of all clarity: bakafile isn't a very descriptive function name. Aim to KISS and be able to understand what the function did purely based on the title

This function seems to attempt to parse a csv like file with either a decimal numbers, a floats with or without exponent and print all lines afterwards. parse_and_print might make a good name.

Second of all, divide and conquer. Adding simple functions can greatly improve readability.

Third magic constants, the file name should be either a parameter or constant.

Fourth, python has introduced a with keyword which simplifies io.

Example result (interpretation of what I thought you were doing):

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

Upvotes: 0

Julien Spronck
Julien Spronck

Reputation: 15433

There are several things wrong with this code but the error message you are getting comes from a line like temp(i)= .... temp(i) is the result of a function call (you call the function temp with argument i) and you cannot assign that result to anything. a[i] = b is valid (you assign the ith element of a) but a(i) = b is not.

Here are some other things that are wrong:

  • lines=f.readline: f.readline is a function but without () you did not actually call that function.
  • You don't need the readline since you already read the file with lines=f.read().split(',')
  • syntax error on your first line: you need a semicolon after def bacfile()

Here is a better way to write that part of the code:

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

Upvotes: 1

dsh
dsh

Reputation: 12214

The error tells you exactly what line is wrong. The first one, that I notice, in your code is this:

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

This line says:

  1. find an object with the name temp
  2. find an object with the name i
  3. call the object (expected to be a function or other callable object) named temp passing it a single argument which is the object referenced by the name i
  4. assign to the preceding function call the result of evaluating the expression on the right hand side of the = operator.
  5. (I won't explain the right hand side since we have already reached the problem)

The left hand side of an assignment must be the name of a variable (or a field, or an entry in a collection). It can not be a function call or other arbitrary expression.

Upvotes: 1

Related Questions