请选择 进入手机版 | 继续访问电脑版
设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
查看: 9374|回复: 4

帮忙看一下,代码那里有问题,谢谢各位了

[复制链接]

1

主题

0

好友

31

积分

新手上路

Rank: 1

发表于 2017-9-1 11:33:43 |显示全部楼层
情况:
首先非常感谢corssin 先生的免费教程,暑假有幸接触到Python,于是想在开学练练手,在参考了github一些代码和Google一些模块的功能后,打算自己写一个关于GPA计算器的程序。
github gpa代码地址为 https://github.com/JasonQSY/JI-GPACal/blob/master/gpacal.py
参考的Python模块操作网址为 http://www.cnblogs.com/lhj588/archive/2012/01/06/2314181.html

想法:通过访问一定格式的xlsx文件后(就是将某些数据固定在某一行,不再通过关键字去索引得到具体的值,具体可参考我写的‘’绩点‘’这一行),获取Excel文件数据,再获取工作表(table)数据,通过所给的学号(id)检索(search)到某一行,之后进行在某一行的数据计算,然后进行学分绩计算,比如将B2的绩点乘B3,再将绩点累加到一个数中,最后得到这个人的学分绩,原本还想将数据那一行Excel的最末尾,命名为学分绩,无奈能力有限,就打算将数据以追加的方式写到文件中。

源代码:
#-*-coding:utf-8-*-

import xlrd as xls

#load your xlsx file
def open_excel(file='grade.xlsx'):
    try:
        data=xls.open_workbook(file)
        return data
    except:
        print 'Please check your file name agian.'

#locate targeted table
def locate_table():
    data = open_excel()
    table1 = data.sheets()[0]
    return table1

#search someone's row
def search(id):
    table=locate_table()
    for i in range(2,table.nrows()):
        if int(table.cell(i,0))==id:
            return i
        else:
            print 'can\'t find targeted object'

#calculate by sheet's character
def cal_someone():
    table=locate_table()
    row=search(id)
    point=0
    credit=0
    for j in range(1,table.ncols):
        thispoint=table.cell(row,1)
        credit+=table.cell(row,j)*thispoint
        point+=thispoint

    currentgpa=credit/point
    return currentgpa

def append_result(id,GPA):   #let each GPA append this file
    file('result.txt','w') #创建文件
    f=file('result.txt','a')
    f.write(id)
    f.write('--')
    f.write(GPA)

#main function
def main():
    open_excel()
    locate_table()

    print 'You should input id to calculate this one\'s GPA'
    id=input()
    search(id)
    gpa=cal_someone()
    append_result(id,gpa)

if __name__=='__main__':
    main()

问题:
1.
我想将file文件名通过手动输入,比如‘grade.xlsx’,但是始终提示文件名找不到,于是我就直接将file给确定下来,请问一下,怎么实现手动输入文件名来确定要操作的文件?

2.测试的时候卡在了search这一行,提示如下:
Connected to pydev debugger (build 171.4694.67)
You should input id to calculate this one's GPA
64
Traceback (most recent call last):
  File "D:\Program Files\PyCharm Community Edition 2017.1.4\helpers\pydev\pydevd.py", line 1591, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "D:\Program Files\PyCharm Community Edition 2017.1.4\helpers\pydev\pydevd.py", line 1018, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "E:/Pycode+/Tools/GPA.py", line 62, in <module>
    main()
  File "E:/Pycode+/Tools/GPA.py", line 57, in main
    search(id)
  File "E:/Pycode+/Tools/GPA.py", line 22, in search
    rows=table.nrows()
TypeError: 'int' object is not callable

3.过程:
   输入文件名-->找到文件(找不到open_excel函数就会出现提示)-->找到文件中的目标工作表(locate_table)-->搜寻某个人(search)-->计算这个人的学分绩-->以追加的形式写入到文件中,保存。(可以的话,想直接写到Excel文件里去)

我看了我的代码,感觉我写的独立的函数是一环套着一环,没有做到真正独立,而且我在主函数里很发蒙:既然第二个函数包含了第一个函数,那我要不要再去调用它?举个例子:我要求输入学号即ID,我将ID传到searche函数里去,但是我的search函数里已经包含了获取工作表的函数(locate_table),而且我的locate_table函数包含了 检查是否存在文件的函数(open_excel),请问一下这样的话,我要是直接调用search函数,是不是前一个函数就不需要调用了?

另外:假使我要实现通过所给文件名来定位目标文件,那么我直接调用search 肯定不行,要进行文件名查找,这样的话我就要先找文件名,然后检验是否能打开文件读取数据(open_excel)这样的话,我就要一个一个将写的函数调用出来,那么函数不就重复了吗?

最后:
假使你们要进行一个程序的设计,你们是怎么搭建整体思路的,怎么利用Python的未知模块的,还有就是你们项目稍微大点,怎么进行单个测试?我是习惯将用不到的给注释掉。。有点尴尬……

求解:()
代码写的有点烂,劳烦各位老师给看一下,我自己测试始终测试不出来,以为是格式问题,但是自己强制将单元表格的格式改成int形式了?stockflow里面说的,Google翻译有点逊,自己英文又有点差,所有觉得没能解决我的问题。求crossin老师给看一下,知道您时间紧张,我也不着急。(尽管这个问题折磨我好多节专业课了>:<)也拜托各位在论坛的前辈们给看一下,谢谢你们。



Excel截图

Excel截图
回复

使用道具 举报

1

主题

0

好友

31

积分

新手上路

Rank: 1

发表于 2017-9-1 17:38:22 |显示全部楼层
测试一下去,一遍注释一遍直接赋值运算,做到了可以计算一行的GPA 了,以下是代码:
前面的int 问题,经我测试是返回了一个class,不能满足运算,后面加上一个.value就可以获得值,接下来打算实现把数据输入到文本,进一步直接输入到Excel文件:
#-*-coding:utf-8-*-

import xlrd as xls

#Load your xlsx file
def open_excel(file='grade.xlsx'):
    try:
        data1=xls.open_workbook(file)
        return data1
    except:
        print 'Please check your file name agian.^-^'

#Locate targeted table
def locate_table():
    data = open_excel()
    table1 = data.sheets()[0]
    return table1

#Search someone's row
def search(id):
    table=locate_table()
    for i in range(2,table.nrows):
        if table.cell(i,0).value==id:
            return i

#Calculate by sheet's character
def cal_someone(id):
    table=locate_table()
    row=search(id)
    point=0
    credit=0
    for j in range(1,table.ncols):
        onepoint=table.cell(1,j).value
        credit+=table.cell(row,j).value * onepoint
        point+=onepoint

    current_GPA=credit/point
    return current_GPA

"""
def append_result(id,GPA):   #let each GPA append this file
    file('result.txt','w') #创建文件
    f=file('result.txt','a')
    f.write(id)
    f.write('--')
    f.write(GPA)
"""

#main function
def main():
    print 'Input ID to calculate GPA'
    oneid=input()

    try:
       g=cal_someone(oneid)
       print g
    except StandardError:
        print 'Check ID again,Thank!'

if __name__=='__main__':
    main()
回复

使用道具 举报

1

主题

0

好友

31

积分

新手上路

Rank: 1

发表于 2017-9-1 23:04:21 |显示全部楼层
本帖最后由 akfree 于 2017-9-1 23:07 编辑

改进了一下午,实现了可以写入文本,有个疑问就是用py2exe打包成的EXE文件只要将生成的exe文件移除dist文件夹中,就会发生闪退

生成EXE文件py 文件如下:
from distutils.core import setup
import py2exe

setup(console=['GPA.py'],
      zipfile=None,
      option={ 'py2exe':{
          'bundle_files':1,
          'dll_excludes':['MSVCP90.dll','w9xpopen.exe']
                        }

            }

      )
代码改进如下:
#-*-coding:utf-8-*-

from xlrd import empty_cell
import xlrd as xls
import os


#Load your xlsx file
def open_excel(file='grade.xlsx'):
    try:
        data1=xls.open_workbook(file)
        return data1
    except:
        print 'Please check your file name agian.^-^'

#Locate targeted table
def locate_table():
    data = open_excel()
    table1 = data.sheets()[0]
    return table1

#Search someone's row
def search(id):
    table=locate_table()
    for i in range(2,table.nrows):
        if table.cell(i,0).value==id:
            return i

#Calculate by sheet's character
def cal_someone(id,assure):
    table=locate_table()
    row=search(id)
    point=0
    credit=0
    time=1
    for j in range(1,table.ncols):
        if isinstance(table.cell(row,j).value,float):
            if assure=='yes' or 'YES':#acquire have empty

                if time<table.ncols:
                    onepoint=table.cell(1,j).value
                    credit+=table.cell(row,j).value * onepoint
                    point+=onepoint
                    time+=1

                else:
                    onepoint = table.cell(1, j).value
                    credit += table.cell(row, j).value * onepoint
                    point += onepoint


    someone=credit/point
    someone_GPA='{:.3f}'.format(someone)
    return someone_GPA


def append_result(id,GPA):   #let each GPA append this file
    f=file('result.txt','a')
    id=str(id)
    GPA=str(GPA)
    f.write(id)
    f.write(' \'s GPA is-->')
    f.write(GPA)
    f.write(os.linesep)

#main function
def main():

    print 'Input ID to calculate GPA'
    oneid=input()
    print 'Does ID\'s row have empty?'
    assure=raw_input()
    try:
        cal_someone(oneid,assure)
    except StandardError:
        raise Exception('Check Again!')
    c_GPA=cal_someone(oneid,assure)
    append_result(oneid,c_GPA)

    if os.path.exists('result.txt'):
        pass
    else:
        open('result.txt','w')

if __name__=='__main__':
    print 'Welcome..'
    while True:
        print 'Calculate Now?(yes/no)'
        reply=raw_input()
        if reply=='yes' or 'YES':
            main()
        else:
            break






回复

使用道具 举报

174

主题

45

好友

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

发表于 2017-9-2 11:33:48 |显示全部楼层
akfree 发表于 2017-9-1 23:04
改进了一下午,实现了可以写入文本,有个疑问就是用py2exe打包成的EXE文件只要将生成的exe文件移除dist文件 ...

exe 要连着整个 dist 文件夹的,里面的文件是有用的
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

1

主题

0

好友

31

积分

新手上路

Rank: 1

发表于 2017-9-3 15:24:04 |显示全部楼层
crossin先生 发表于 2017-9-2 11:33
exe 要连着整个 dist 文件夹的,里面的文件是有用的

谢谢crossin先生
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-3-29 19:40 , Processed in 0.029338 second(s), 30 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部