python:最后一行field_pat.sub(replacement,text)是不是写错了,

Python018

python:最后一行field_pat.sub(replacement,text)是不是写错了,,第1张

应该没错,这里sub函数的第一个参数就是replacement函数的返回值,一个字符串。

当然,鉴于replacement函数可能返回空字符串,不太建议这样直接使用,最好在前面先判断一下,或者放在try-except语句中。

作为代码例子,可能还没讲到异常处理这一章节,所以不完善是正常的。

#coding=utf-8

records = []

record = {}

with open("data.txt") as f:

    while True:

        line = f.readline()

        if not line:

            if len(record)!= 0: records.append(record)

            break

        field = line[line.find(":") + 1:].strip()

        if line.startswith("ScopeId"):

            if len(record)!= 0: records.append(record)

            record = {}

            record["ScopeId"] = field

        elif line.startswith("Name"):

            record["Name"] = field

        elif line.startswith("Free"):

            record["Free"] = field

        elif line.startswith("InUse"):

            record["InUse"] = field

        elif line.startswith("PercentageInUse"):

            record["PercentageInUse"] = field

# 设置缺省项            

for r in records:

    r.setdefault("InUse", 0)

    r.setdefault("PercentageInUse", 0)

    r.setdefault("Name", "")

    r.setdefault("Free", 0)

    

print records

假如你的5文件在同一个文件夹中,路径为path

file_name_list = ['usa', 'china', 'uk', 'canada', 'japan']

data_list = []

for i in file_name_list:

data_list.append(pd.read_excel(path + '/%s.xlsx' % i))

data = pd.concat(data_list)