Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #103341
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: avoid for loop calling Generator function |
| Date | 2016-02-22 14:34 +0100 |
| Organization | None |
| Message-ID | <mailman.40.1456148110.20994.python-list@python.org> (permalink) |
| References | <e5e4a934-4eeb-46ed-892f-cda9e903c1cd@googlegroups.com> |
Arshpreet Singh wrote:
> Hi, I am converting PDF into text file, I am using following code.
>
> from pypdf2 import PdfFileReader
>
> def read_pdf(pdfFileName):
>
> pdf = PdfFileReader(pdfFileName)
>
> yield from (pg.extractText() for pg in pdf.pages)
>
> for i in read_pdf('book.pdf'):
> print(i)
>
> I want to avoid for loop , I also tried to create another function and
> call read_pdf() inside that new function using yield from but I think I am
> missing real picture here
While it is possible to replace the loop with
next(filter(print, read_pdf("book.pdf")), None)
or the slightly less convoluted
sys.stdout.writelines(map("{}\n".format, read_pdf("book.pdf")))
the for loop is the obvious and therefore recommended solution. Personally,
I would also replace
> yield from (pg.extractText() for pg in pdf.pages)
with the good old
for pg in pdf.pages:
yield pg.extractText()
and reserve the generator expression for occasions where it has a
demonstrable advantage in readability.
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
avoid for loop calling Generator function Arshpreet Singh <arsh840@gmail.com> - 2016-02-22 03:15 -0800
Re: avoid for loop calling Generator function Peter Otten <__peter__@web.de> - 2016-02-22 14:34 +0100
Re: avoid for loop calling Generator function Arshpreet Singh <arsh840@gmail.com> - 2016-02-22 07:38 -0800
Re: avoid for loop calling Generator function Chris Angelico <rosuav@gmail.com> - 2016-02-23 02:46 +1100
Re: avoid for loop calling Generator function Ian Kelly <ian.g.kelly@gmail.com> - 2016-02-22 09:11 -0700
csiph-web