如何正确调用函数

时间:2016-09-12 04:43:36

标签: python python-3.x

这是具有四个参数的函数。

import urllib
import xlrd
from xlwt import Workbook

def getClose(i ,p, f):
    workbook = xlrd.open_workbook('test1.xlsx');
    sheet=workbook.sheet_by_index(0);

    num_rows = sheet.nrows -1;

    inputI=str(i);
    inputP=str(p);
    inputF=f;

    writeBook= Workbook();
    writeSheet= writeBook.add_sheet('Close Price');
    for i in range(0,num_rows+1):
        inputS=sheet.cell_value(i,0);
        address='http://www.google.com/finance/getprices?q='+inputS+'&i='+inputI+'&p='+inputP+'d&f='+inputF;
        response = urllib.request.urlopen(address);
        data = response.readlines();
        newData = data[7:len(data)];
        result=[];
        amount =0;
        for line in newData:
            content =str((line.decode("utf-8", errors='ignore').split("\n")[0]));
            result.insert(amount,content);
            amount = amount +1;
        for n in range(amount):
            writeSheet.write(n,i,result[n]);
    writeBook.save('close price.xls');

但是现在我想从excel获取参数q,我该怎么办? 我知道如何使用三个参数来编写它。

#include "stdio.h"
int list_threads(kv_item *item, xbuf_t *reply)
{
  Thread *thread = (Thread*)item->val;

  xbuf_t thread_li;
  xbuf_init(&thread_li);

  //using sprintf-like formatting
  xbuf_xcat(&thread_li, 
  "<li>"
   "<a href='/?forum_simple/act=t/id=%llu'>%s</a> (%lu)"
  "</li>",
  thread->id, thread->title.ptr, thread->posts.nbr_items
  );

  char *pos = (char*)xbuf_findstr(reply, "<!--tpl-->");
  if (pos) xbuf_insert(reply, pos, thread_li.len, thread_li.ptr);
  printf("-----------listing threads------\n");
  xbuf_free(&thread_li);

  return 1;
}

我该怎么办?真的很感激。

1 个答案:

答案 0 :(得分:0)

不建议在单个函数中执行太多操作。查看该功能,主要有三个操作:

  1. 从电子表格(test1.xlsx)获取查询参数(q)检索
  2. 并从网页解析值将解析后的结果保存在
  3. 电子表格(close price.xls)
  4. 我建议只为#2创建一个函数getClose,然后在一个主循环中使用它,该循环将从q读取参数test1.xlsx并将结果写入close price.xls。伪代码如:

    # THIS IS PSEUDO-CODE, not python...
    open(input_spreadsheet)
    open(output_spreadsheet)
    for row in input_spreadsheet:
        q = parse_row(row)
        result = getClose(<adjust parameters after function rewrite>)
        write_row(output_spreadsheet)