鱼C论坛

 找回密码
 立即注册
查看: 1674|回复: 4

请大神帮忙看看,为啥出错了

[复制链接]
发表于 2022-6-2 19:51:18 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
原代码如下:
#! python3
# combinePdfs.py - Combines all the PDFs in the current working directory into a single PDF.
import PyPDF2, os
# 找到文件夹中所有的PDF文件
pdfFiles = []
for filename in os.listdir('.'):
    if filename.endswith('.pdf'):
        pdfFiles.append(filename)
pdfFiles.sort(key/str.lower)

pdfWriter = PyPDF2.PdfFileWriter()

#打开每个PDF文件
for filename in pdfFiles:
    pdfFileObj = open(filename, 'rb')
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj)

#添加每一页
    for pageNum in range(1, pdfReader.numPages):
        pageObj = pdfReader.getPage(pageNum)
        pdfWriter.addPage(pageObj)

#保存结果
pdfOutput = open('allminutes.pdf', 'wb')
pdfWriter.write(pdfOutput)
pdfOutput.close()
但是出现了这样报错:
NameError: name 'key' is not defined
怎样解决呢?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-6-2 20:11:14 | 显示全部楼层


pdfFiles.sort(key/str.lower) 这行代码参数应该要引号吧?

这里的 key 没定义才会导致你报错 ,其他的不太清楚,没用过这个模块

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-6-2 20:15:48 | 显示全部楼层
help(list.sort)
Help on method_descriptor:

sort(self, /, *, key=None, reverse=False)
    Sort the list in ascending order and return None.
   
    The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
    order of two equal elements is maintained).
   
    If a key function is given, apply it once to each list item and sort them,
    ascending or descending, according to their function values.
   
    The reverse flag can be set to sort in descending order.

我看不懂,你参考参考
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-6-2 20:39:48 | 显示全部楼层
pdfFiles.sort(key=str.lower)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-6-2 20:52:44 | 显示全部楼层
将pdfFiles.sort(key/str.lower) 改成pdfFiles.sort(reverse=True),
也可以指定 reverse 关键字参数为 True,让 sort()按逆序排序
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-8 04:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表