使用另一个函数内部函数的输出的Python
对不起发表另一个重复的问题,但我一直在处理这个基本概念,尽管试图从别人的例子中学习,但我仍然不明白。使用另一个函数内部函数的输出的Python
我想要做的是使用PyPDF2获取PDF的内容并将它们写入CSV,并且我正在逐步构建和测试我的程序。我在这里我想点我的节目做两件事情:
1抓斗从PDF文件中的文本
- 输出抓起文本在一个单一入口csv文件。
现在,这里是我缺乏基本的编程概念开始显示。这里的代码:
import csv
import os
import PyPDF2
os.chdir('C:/Users/User/Desktop')
def getText(happy_file):
pdf_file_obj = open(happy_file, 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file_obj)
pdf_reader.numPages #optional
page_obj = pdf_reader.getPage(0)
return page_obj.extractText()
def writeToCSV(happy_file):
output_file = open('myfinalfile.csv', 'w', newline ='')
output_writer = csv.writer(output_file)
output_writer.writerow([str(getText())])
output_file.close()
我有两个函数来完成这个任务getText和writeToCSV。我的目标是对它进行编程,以便我所需要做的就是调用writeToCSV('anyfile.pdf'),并让它使用这两个函数来提取数据并将其放入csv中。 happy_file目前是两个函数的参数,但我知道需要改变。我在想,我需要第三个main()函数,该函数以变量包含在main()中的方式合并了这两个函数。这可能是我没有看到的基本方面。另一个预感是必须有一种方法可以让getText在writeToCSV中返回一个可用的变量(实际上这是本文的全部目的)。我之前在变量前面使用过'global'来访问其他函数中的变量,但我听说这是一个坏主意。
我知道我可以让它成为一个函数,但随着事情变得越来越复杂(即我想通过一堆pdf来循环),我想让我的程序在更小的块中,每个代表一个步骤办法。也许我在理解函数方面真的很糟糕。也许看到我的实际代码以正确的方式重新格式化将使它“点击”我。
搞清楚这将是写好结构化程序的正确方向迈出的重要一步,而不仅仅是计算机执行的一个巨大方向列表。
下面是其他职位的名单我研究:
Python - Passing a function into another function
using the output of a function as the input in another function python new to coding
Python - output from functions?
Python: accessing returned values from a function, by another function
谢谢!
您需要将happy_file
传递给writeToCSV
函数中的getText
函数。
然后,您可以拨打writeToCSV
,如代码示例底部所示。
import csv
import os
import PyPDF2
os.chdir('C:/Users/User/Desktop')
def getText(happy_file):
pdf_file_obj = open(happy_file, 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file_obj)
pdf_reader.numPages #optional
page_obj = pdf_reader.getPage(0)
return page_obj.extractText()
def writeToCSV(happy_file):
output_file = open('myfinalfile.csv', 'w', newline ='')
output_writer = csv.writer(output_file)
output_writer.writerow([str(getText(happy_file))])
output_file.close()
writeToCSV("anyfile.pdf")
或者,如果出于某种原因,你宁愿一个main()
功能,你可以做这样的:
import csv
import os
import PyPDF2
os.chdir('C:/Users/User/Desktop')
def getText(happy_file):
pdf_file_obj = open(happy_file, 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file_obj)
pdf_reader.numPages #optional
page_obj = pdf_reader.getPage(0)
return page_obj.extractText()
def writeToCSV(happy_file):
output_file = open('myfinalfile.csv', 'w', newline ='')
output_writer = csv.writer(output_file)
output_writer.writerow([str(getText(happy_file))])
output_file.close()
def main():
writeToCSV("anyfile.pdf")
if __name__ == "__main__":
main()
究竟什么是你问?你需要一种方法来获得你必须正确工作的方式,或者你是否在寻找一种更好的/不同的方式来完全解决你的问题? –
@AndrewMcKernan我只需要一种方法使其正常工作,以帮助巩固我的理解如何在另一个函数中使用变量。 – Kevin