Reputation: 3
So, I have a Text-File and I want to print out just the Paragraphs of that File. My code seems to be working, but everytime when there is a empty line in the txt-file, my Output shows me "None". I understand it has something to do with the return statement, but I really dont get where my mistake is Here is my Code:
class ByParagraph:
def __init__(self,iterable):
self.iterable = iterable
def __iter__(self):
return self
def __next__(self):
for line in self.iterable:
if line.isspace():
break
else:
return "".join(line.rstrip())
else:
raise StopIteration()
with open("example.txt") as f:
for p in ByParagraph(f):
print(p)
Here is the output:
None
This is an a sentence.
None
This is another sentence.
Followed by yet another one.
None
None
This is not the last sentence.
This one neither.
None
None
None
This one is the last one.
And it should look like this
This is an a sentence.
This is another sentence. Followed by yet another one.
This is not the last sentence. This one neither.
This one is the last one.
I was expecting to get an Output without the "none" Statements.
Upvotes: 0
Views: 45
Reputation: 3
In the __init__ function, you can add some logic to automatically remove empty lines, like so:
def __init__(self,iterable):
iterable=iterable.split('\n')
while '' in iterable:
iterable.remove('')
new_iterable=''
for i in iterable:
new_iterable+=i
self.iterable=new_iterable+'\n'
Upvotes: 0
Reputation: 41
You can use the filter() function on text.splitlines() to remove empty lines and the result is joined back with newline separator:
lines = filter(lambda x: x.strip() != "", text.splitlines())
text = "\n".join(lines)
Hope this helps.
Upvotes: 1