python函数读取文件和正则表达式

时间:2016-03-14 18:14:44

标签: 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()

然而,当执行该函数时,我收到错误“无法分配给函数调用”这是什么意思,我该如何解决?

3 个答案:

答案 0 :(得分:1)

此代码存在一些问题,但您收到的错误消息来自temp(i)= ...之类的行。 temp(i)是函数调用的结果(您使用参数temp调用函数i)并且您无法将该结果分配给任何内容。 a[i] = b有效(您指定了a的第i个元素),但a(i) = b不是。

以下是其他一些错误:

  • lines=f.readline:f.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 :(得分:1)

错误告诉您确切的错误行。在我的代码中,我注意到的第一个是:

public enum ListType { LIST1, LIST2,..... };
...
EnumMap<ListType, List<DictionaryELement>> lists = new EnumMap<>(ListType.class);
...

for (ListType t : ListType.values())
{
    lists.put(t,new ArrayList<DictionaryELement>());
}

这句话说:

  1. 找到名为temp (i)= open ('A157038027_S2TIB_2b.txt','r')
  2. 的对象
  3. 找到名为temp
  4. 的对象
  5. 调用名为i的对象(期望是函数或其他可调用对象),向其传递一个参数,该参数是名称temp引用的对象
  6. 为前面的函数调用指定评估i运算符右侧表达式的结果。
  7. (由于我们已经遇到问题,我不会解释右侧)
  8. 作业的左侧必须是变量的名称(或字段或集合中的条目)。它不能是函数调用或其他任意表达式。

答案 2 :(得分:0)

因为无论如何都给出了答案。让我们谈谈在更广泛的意义上改进你的代码。

首先清晰度:bakafile不是一个非常具有描述性的功能名称。瞄准KISS,能够理解纯粹基于标题的功能

此函数似乎尝试使用十进制数字,带或不带指数的浮点数解析csv like文件,然后打印所有行。 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')