Peanut Jams
Peanut Jams

Reputation: 384

Print out line number of a text?

Are there any way to print out the text line number in outputs?

I have a sample text (the first 3 sentences):

There was no possibility of taking a walk that day

We had been wandering indeed in the leafless shrubbery an hour in the morning but since dinner (Mrs 
Reed when there was no company dined early) the cold winter wind had brought with it clouds so sombre 
and a rain so penetrating that further out door exercise was now out of the question

I was glad of it I never liked long walks especially on chilly afternoons dreadful to me was the 
coming home in the raw twilight with nipped fingers and toes and a heart saddened by the chidings of 
Bessie the nurse and humbled by the consciousness of my physical inferiority to Eliza John and 
Georgiana Reed

I currently got this output:

9 out of 10 words contain no 'e'.
30 out of 53 words contain no 'e'.
31 out of 56 words contain no 'e'.

But i can't find a way to also include the line numbers at the beginning such as:

0: 9 out of 10 words contain no 'e'.
1: 30 out of 53 words contain no 'e'.
2: 31 out of 56 words contain no 'e'.

The codes (Tried using enumerate(line) but doesn't work):

with open("jane_eyre_sentences.txt") as line:
     low = line.lower()
     words = low.split()
     app = []
     for word in words:
        if "e" not in word:
             app.append(word)
        print("%d:%s"%(i, wordy) + "" + str(len(app)) + " out of " + str(len(words)) + " words contain no 'e'." )

Thanks for reading.!

Upvotes: 3

Views: 148

Answers (4)

alani
alani

Reputation: 13079

Not exactly the one-liner solution, but you could make yourself a handy NumberedLineWriter class that puts a line number at the start of every line. You can then put it into a module and reuse this in any code that needs it.

class NumberedLineWriter:

    def __init__(self, first=0):
        self.i = first

    def __call__(self, *args, **kwargs):
        print(self.i, *args, **kwargs)
        self.i += 1

    def __enter__(self):
        return self

    def __exit__(*_):
        pass

Maybe put it in its own module linewriter.py and then when you need it you can do:

from linewriter import NumberedLineWriter

Then when you want to use it, you can just use an instance of it in place of regular print inside a with block, for example:

with NumberedLineWriter() as myprint:
    myprint("hello")
    myprint("world")

Prints

0 hello
1 world

Or in this case, combine the with clauses into one:

with open('jane_eyre_sentences.txt', 'r') as file, NumberedLineWriter() as myprint:
    for line in file:
        ....
        myprint(...whatever...)

It doesn't matter how many or few times you call myprint inside each iteration of your for loop, because the myprint contains its own counter to keep track of the line number, and is not tied into your file iterator in any way.

Upvotes: 0

Tasnuva Leeya
Tasnuva Leeya

Reputation: 2795

with open("jane_eyre_sentences.txt") as file:
read_file = file.readlines()
for i, word in enumerate(read_file):
    low = word.lower()
    words = low.split()
    app = [w for w in words if 'e' not in w]
    print("{}: {} out of {} words contain no 'e'.".format(i, len(app), len(words)))

Upvotes: 1

Patrick Artner
Patrick Artner

Reputation: 51683

What you call line is in fact the file - not a text line.

Doing low = line.lower() on it should not even work:

Exception has occurred: AttributeError
'_io.TextIOWrapper' object has no attribute 'lower'

Try

with open("jane_eyre_sentences.txt") as file:
    for nr, line in enumerate(file): 
        words = line.lower().split()
        words_without_e = [ w for w in words if 'e' not in w]

        print(f"{nr}: {len(words_without_e)} out of {len(words)} words contain no 'e'.")

Output:

0: 9 out of 10 words contain no 'e'.
1: 0 out of 0 words contain no 'e'.
2: 8 out of 18 words contain no 'e'.
3: 11 out of 19 words contain no 'e'.
4: 11 out of 16 words contain no 'e'.
5: 0 out of 0 words contain no 'e'.
6: 12 out of 19 words contain no 'e'.
7: 11 out of 19 words contain no 'e'.
8: 8 out of 16 words contain no 'e'.
9: 0 out of 2 words contain no 'e'.

I used

with open("jane_eyre_sentences.txt","w") as file:
    file.write("""There was no possibility of taking a walk that day

We had been wandering indeed in the leafless shrubbery an hour in the morning but since dinner (Mrs 
Reed when there was no company dined early) the cold winter wind had brought with it clouds so sombre 
and a rain so penetrating that further out door exercise was now out of the question

I was glad of it I never liked long walks especially on chilly afternoons dreadful to me was the 
coming home in the raw twilight with nipped fingers and toes and a heart saddened by the chidings of 
Bessie the nurse and humbled by the consciousness of my physical inferiority to Eliza John and 
Georgiana Reed""")

as input file.

Upvotes: 3

Alok
Alok

Reputation: 9008

Try this out, for checking out the next, you should use readlines(), and then iterate over your lines, like this:

with open('jane_eyre_sentences.txt', 'r') as myfile:
    lines = myfile.readlines()

for line in lines:
    if 'this' in line: #Your criteria here to skip lines
        continue

    #Do something here

Upvotes: 0

Related Questions