我试图从文本文件中提取原始数据,在处理完原始数据后,我想将其导出到另一个文本文件中。下面是我为这个过程编写的python代码。为此,我使用了python3中的“petl”包位置.txt'是原始数据文件。在
import glob, os
from petl import *
class ETL():
def __init__(self, input):
self.list = input
def parse_P(self):
personids = None
for term in self.list:
if term.startswith('P'):
personids = term[1:]
personid = personids.split(',')
return personid
def return_location(self):
location = None
for term in self.list:
if term.startswith('L'):
location = term[1:]
return location
def return_location_id(self, location):
location = self.return_location()
locationid = None
def return_country_id(self):
countryid = None
for term in self.list:
if term.startswith('C'):
countryid = term[1:]
return countryid
def return_region_id(self):
regionid = None
for term in self.list:
if term.startswith('R'):
regionid = term[1:]
return regionid
def return_city_id(self):
cityid = None
for term in self.list:
if term.startswith('I'):
cityid = term[1:]
return cityid
print (os.getcwd())
os.chdir("D:\ETL-IntroductionProject")
print (os.getcwd())
final_location = [['L','P', 'C', 'R', 'I']]
new_location = fromtext('locations.txt', encoding= 'Latin-1')
stored_list = []
for identifier in new_location:
if identifier[0].startswith('L'):
identifier = identifier[0]
info_list = identifier.split('_')
stored_list.append(info_list)
for lst in stored_list:
tabling = ETL(lst)
location = tabling.return_location()
country = tabling.return_country_id()
city = tabling.return_city_id()
region = tabling.return_region_id()
person_list = tabling.parse_P()
for person in person_list:
table_new = [location, person, country, region, city]
final_location.append(table_new)
totext(final_location, 'l1.txt')
然而,当我使用petl的“totext”函数时,它会抛出一个“断言错误”。在
AssertionError: template is required I am unable to understand what the fault is. Can some one please explain the problem I am facing and what I should be doing ?
toext函数的template参数不是可选的没有关于如何写入行的默认格式在这种情况下,必须提供一个模板。在这里查看文档以获取下一个示例:https://petl.readthedocs.io/en/latest/io.html#text-files
模板描述了它使用字段头来描述事情的每一行的格式,您也可以选择传入序言来编写标题。在您的案例中,基本模板是:
table_new_template = "{L} {P} {C} {R} {I}" totext(final_location, 'l1.txt', template=table_new_template)
相关问题 更多 >
编程相关推荐