Search code examples
pythonfiletextsavesentence

Appending the length of sentences to file


I found the length and index and i want save all of them to new file:

example: index sentences length

my code

file = open("testing_for_tools.txt", "r")
lines_ = file.readlines()
for line in lines_:
    lenght=len(line)-1
    print(lenght)
for item in lines_:
    print(lines_.index(item)+1,item)

output:

64
18
31
31
23
36
21
9
1
1 i went to city center, and i bought xbox5 , and some other stuff

2 i will go to gym !

3 tomorrow i, sill start my diet!

4 i achive some and i need more ?

5 i lost lots of weights؟

6 i have to , g,o home,, then sleep  ؟

7 i have things to do )

8 i hope so

9 o

desired output and save to new file :

1 i went to city center, and i bought xbox5 , and some other stuff 64
2 i will go to gym ! 18 

Solution

  • This can be achieved using the following code. Note the use of with ... as f which means we don't have to worry about closing the file after using it. In addition, I've used f-strings (requires Python 3.6), and enumerate to get the line number and concatenate everything into one string, which is written to the output file.

    with open("test.txt", "r") as f:
        lines_ = f.readlines()
    
    with open("out.txt", "w") as f:
        for i, line in enumerate(lines_, start=1):
            line = line.strip()
            f.write(f"{i} {line} {len(line)}\n")
    

    Output:

    1 i went to city center, and i bought xbox5 , and some other stuff 64
    2 i will go to gym ! 18
    

    If you wanted to sort the lines based on length, you could just put the following line after the first with block:

    lines_.sort(key=len)
    

    This would then give output:

    1 i will go to gym ! 18
    2 i went to city center, and i bought xbox5 , and some other stuff 64