我试图看看如何以可以使用继承方法的方式构建脚本。我对python很新。我的问题是在另一个class-def中使用一个类中的变量。我刚刚了解了super
函数,我认为我没有正确使用它,因为它不断打印并重新计算它所取代的所有内容。
假设我有一堆消息来自用逗号分隔的文本文件,它给了我不同的信息。我希望能够获取该文本文件...
这是我正在使用的玩具结构
import bunch of stuff
data = [] #empty because we will store data into it
#Reads a CSV file and return it as a list of rows
def read_csv_file(filename):
"""Reads a CSV file and return it as a list of rows."""
for row in csv.reader(open(filename)):
data.append(row)
return data
with open(path_in + data_file) as csvfile:
read_it = list(csv.reader(csvfile, delimiter=','))
#Counts the number of times a GPS command is observed
def list_msg_type_countdata):
"""Counts the number of times a GPS command is observed.
Returns a dictionary object."""
msg_count = dict()
for row in data:
try:
msg_count[row[0]] += 1
except KeyError:
msg_count[row[0]] = 1
return msg_count
print(list_msg_type_count(read_it))
print ("- - - - - - - - - - - - -")
class CreateWorkbook:
def openworkbook(self, data):
global output_filename
output_filename = input('output filename:')
global workbook
workbook = xlsxwriter.Workbook(path_out + output_filename + '_' + command_type +'.xlsx')
self.worksheet = workbook.add_worksheet()
#formatting definitions
global bold
bold = workbook.add_format({'bold': True})
global date_format
date_format = workbook.add_format({'num_format': "m/d/yyyy hh:mm:ss"})
global time_format
time_format = workbook.add_format({'num_format': "hh:mm:ss"})
def closeworkbook_gprmc(self, data):
print('closeworkbook')
#pull data from process_msg1
(i1, i2, i3) = messagetype.process_msg1(data)
#sets up the header row
self.worksheet.write('A1','item1',bold)
self.worksheet.write('B1', 'item2',bold)
self.worksheet.write('C1', 'item3',bold)
self.worksheet.autofilter('A1:C1') #dropdown menu created for filtering
# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook
for c, col in enumerate(data):
self.worksheet.write_column(r,0, i1)
self.worksheet.write_column(r,1, i2)
self.worksheet.write_column(r,2, i3)
workbook.close()
f.close()
print('XLSX file named ' + output_filename + '_' + command_type +' was created')
def closeworkbook_msg2(self, data):
#pull data from process_msg2
(i1, i2, i3, i4) = messagetype.process_msg2(data)
#sets up the header row
self.worksheet.write('A1','item1',bold)
self.worksheet.write('B1', 'item2',bold)
self.worksheet.write('C1', 'item3',bold)
self.worksheet.write('C1', 'item4',bold)
self.worksheet.autofilter('A1:C1') #dropdown menu created for filtering
# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook
for c, col in enumerate(data):
self.worksheet.write_column(r,0, i1)
self.worksheet.write_column(r,1, i2)
self.worksheet.write_column(r,2, i3)
self.worksheet.write_column(r,3, i4)
workbook.close()
f.close()
print('XLSX file named ' + output_filename + '_' + command_type + ' was created')
class ConvertFile
def convert2csv(self, data):
# set path to folder containing xlsx files
os.chdir(path_out)
# find the file with extension .xlsx
xlsx = glob.glob(output_filename + '_' + command_type + '.xlsx')
# create output filenames with extension .csv
csvs = [x.replace('.xlsx','.csv') for x in xlsx]
# zip into a list of tuples
in_out = zip(xlsx,csvs)
# loop through each file, calling the in2csv utility from subprocess
for xl,csv in in_out:
out = open(csv,'w')
command = 'c:/python34/scripts/in2csv %s\\%s' % (path_out,xl)
proc = subprocess.Popen(command,stdout=out)
proc.wait()
out.close()
print('CSV file named ' + output_filename + '_' + command_type + ' was created')
def convert2kml(self, data):
#Input the file name.
h = open(path_out + output_filename + '_' + command_type + '.csv')
with h as csvfile2:
data2 = csv.reader(csvfile2,delimiter=',')
next(data2)
#Open the file to be written.
g = open(output_filename + '_' + command_type +'.kml','w')
g.write("<?xml version='1.0' encoding='UTF-8'?>\n")
g.write("<kml xmlns='http://earth.google.com/kml/2.1'>\n")
g.write("<Document>\n")
g.write(" <name>" + output_filename + '_' + command_type + '.kml' +"</name>\n")
for row in data2:
g.write(" <Placemark>\n")
g.write("<TimeStamp><when>" + str(row[0]) + "</when></TimeStamp>\n")
g.write(" <Point>\n")
g.write(" <coordinates>" + str(row[2]) + "," + str(row[1]) + "</coordinates>\n")
g.write(" </Point>\n")
g.write(" </Placemark>\n")
g.write("</Document>\n")
g.write("</kml>\n")
g.close()
h.close()
print('and ' + output_filename + '_' + command_type +'.kml was created,too!')
class MessageType:
def process_msg1(self,data)
item1 = []
item2 = []
item3 = []
print('printing stuff')
for r in data:
if row[0] == 'msg type1'
item1.append('calculations')
item2.append('calculations')
item3.append('calculations')
print('calculations done')
return(array(item1),array(item2),array(item3))
def process_msg2(self,data)
item1 = []
item2 = []
item3 = []
item4 = []
print('printing stuff')
for r in data:
if row[0] == 'msg type1'
item1.append('calculations')
item2.append('calculations')
item3.append('calculations')
item4.append('calculations')
print('calculations done')
return(array(item1),array(item2),array(item3),array(item4))
class PrintMSG(MessageType):
def process_msg1(self, data):
(i1, i2, i3) = super(PrintMSG, self).process_msg1(data)
print('printing plus plotting using variables from class Message')
def process_msg2(self, data):
(i1, i2, i3,i4) = super(PrintMSG, self).process_msg2(data)
print('printing plus plotting using variables from class Message')
#processing piece
keep_asking = True
while keep_asking:
command_type = input("What message type do you want to look at?")
if command_type == 'msg type1':
createworkbook = CreateWorkbook()
createworkbook.openworkbook(data)
msg = MessageType()
print_msg = PrintMSG()
print_msg.process_msg1(data)
createworkbook.closeworkbook_msg1(data)
convert2csv(data)
convert2kml(data)
elif command_type == 'msg type2':
createworkbook = CreateWorkbook()
createworkbook.openworkbook(data)
msg = MessageType()
print_msg = PrintMSG()
print_msg.process_msg2(data)
createworkbook.closeworkbook_msg2(data)
convert2csv(data)
convert2kml(data)
else:
print("Invalid type:", command_type)
wannalook = input('Want to look at another message or no?')
if not wannalook.startswith('y'):
keep_asking = False
答案 0 :(得分:1)
代码有点大,有许多东西不起作用或无法改进。作为首发,请上课$.Ajax({
url: 'controller/action',
type: 'POST',
success: function(data) {
$('#frmSubTors').html(data);
}
}).done(function() {
// do my other stuff here
});
。您需要始终使用CreateWorkbook
作为方法的第一个参数。 (有一些例外,但它们在这里不相关。)为了能够在一个方法中使用另一个方法中定义的变量,您需要在它们前面添加self
:
self.
这没有多大意义:
class CreateWorkbook:
def openworkbook(self, data):
self.output_filename = input('output filename:')
self.workbook = xlsxwriter.Workbook(path_out + output_filename + '_' + command_type +'.xlsx')
self.worksheet = workbook.add_worksheet()
def closeworkbook_msg1(self, data):
#sets up the header row
self.worksheet.write('A1','item1',bold)
self.worksheet.write('B1', 'item2',bold)
self.worksheet.write('C1', 'item3',bold)
self.worksheet.autofilter('A1:C1') #dropdown menu created for filtering
# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook
for c, col in enumerate(data):
self.worksheet.write_column(r,0, i1)
self.worksheet.write_column(r,1, i2)
self.worksheet.write_column(r,2, i3)
self.workbook.close()
print('XLSX file named ' + output_filename + '_' + command_type +' was created')
def closeworkbook_msg2(self, data):
#sets up the header row
self.worksheet.write('A1','item1',bold)
self.worksheet.write('B1', 'item2',bold)
self.worksheet.write('C1', 'item3',bold)
self.worksheet.write('C1', 'item4',bold)
self.worksheet.autofilter('A1:C1') #dropdown menu created for filtering
# Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook
for c, col in enumerate(data):
self.worksheet.write_column(r,0, i1)
self.worksheet.write_column(r,1, i2)
self.worksheet.write_column(r,2, i3)
self.worksheet.write_column(r,3, i4)
self.workbook.close()
print('XLSX file named ' + output_filename + '_' + command_type + ' was created')
我会将其解释为:
f = open(path_in + data_file)
read_it = read_csv_file(path_in + data_file)
with f as csvfile:
readCSV = csv.reader(csvfile,delimiter=',')