2

I read the .txt file and then picked a few words from in different sentences and after reading the text and printed them. Now I want to take that output as input and then join line1+line2, line3+line4, .....). And also when I am printing the output I don't want the first word from the second line (which means from the even number of lines as in line 2, line 4 ....) and replace that with ';'. Here is the output that I printed from the text file.

Jack love Dancing
Jack is a dancer
Tony likes candy
Tony ate candy
Jack love Dancing
Jack is a dancer
Tony likes candy
Tony ate candy

Now I want to store that in .txt file and print as

Jack love Dancing ; is a dancer.
Tony likes candy ; ate candy.
Jack love Dancing ;is a dancer.
Tony likes candy ; ate candy.

I have gone through how to join two lines from the text file, but I am not sure how to save the output from print statement to .txt file (in the program) and remove the first word by replacing with ';' Code

with open('file.txt') as f:
out = [x for x in f.read().split("\n") if x.strip() != ""] 
for line1, line2 in list(zip(out, out[1:]))[::2]:
    print(" ".join([line1, line2]))

output for the above code

Jack love Dancing Jack is a dancer
Tony likes candy Tony ate candy
Jack love Dancing Jack is a dancer
Tony likes candy Tony ate candy

Any suggestions would be appreciated. Thanks in advance.

sri
  • 75
  • 8

3 Answers3

1

Try this :

with open('file.txt') as f:
    out = [x for x in f.read().split("\n") if x.strip() != ""] 
    for line1, line2 in list(zip(out, out[1:]))[::2]:
        line1 = line1 + ';'
        line2 = line2.split(' ')
        line = ''
        for x in range(1,len(line2)):
            line = line + line2[x] + ' '
        line = line[:-1] + '.' 
        print(" ".join([line1, line]))

change print line with this:

with open('new.txt' , 'a+') as file:
    file.write(" ".join([line1, line]) + '\n')

This code add output in txt file only one time :

temp_list = ''
with open('temp.txt') as f:
    out = [x for x in f.read().split("\n") if x.strip() != ""] 
    for line1, line2 in list(zip(out, out[1:]))[::2]:
        line1 = line1 + ';'
        line2 = line2.split(' ')
        line = ''
        for x in range(1,len(line2)):
            line = line + line2[x] + ' '
        line = line[:-1] + '.' 
        temp_list += " ".join([line1, line]) + '\n'

with open('new.txt' , 'w') as file:
    file.write(temp_list)
Bhargav Desai
  • 941
  • 1
  • 5
  • 17
  • Actually I have input.txt file and from that I printed output which is "Jack love Dancing Jack is a dancer Tony likes candy Tony ate candy Jack love Dancing Jack is a dancer Tony likes candy Tony ate candy" from this I want to join the lines. For this, one way I thought is to store the printed output in the new.txt file (maybe from print statement to .txt file)and from this text file join the lines. but here I am not sure how to store the printed output into .txt file. Can you also help me with that. – sri Jun 05 '20 at 06:29
  • now this write output into the `new.txt` file. – Bhargav Desai Jun 05 '20 at 06:37
  • It worked but when I am executing multiple times, results are storing multiple times. Even If I execute n number of times I need the result to be stored only once. Is there any possible way to do so? – sri Jun 05 '20 at 07:44
  • I tried this way "out= " ".join ([g1, c1, d1, e1, f1]) with open('outfile.txt' , 'w') as file: file.write(out)" where out is the output of the read file and I am trying to place it .txt file. Still I cannot see my out in outile.txt but when I print the "out "statement I can see the output. – sri Jun 05 '20 at 08:01
  • please explain more. and what is [g1,c1,d1,e1,f1] ? – Bhargav Desai Jun 05 '20 at 08:05
  • So there are multiple lines in a text file. From that file I picked different words and tried to join those words and print them in one line. In the above text file that I provided, words are such as "jack" "loves" "dancing" are the words located at different positions and I tried to select those words and joined them.Finally stored the result in out variable. – sri Jun 05 '20 at 08:09
  • by using your code , if i am create some variable with random words after that join words in out variable and store into the file. it works , so i can't find error. – Bhargav Desai Jun 05 '20 at 08:15
  • I used f.sort (in the second after opening the file temp.txt) it is showing str has no object to sort Do you have any idea which function or format to use for sorting the text file. – sri Jun 07 '20 at 17:29
  • `sort` method only work for the list. you can create list using `for` loop and `f.readlines()` from the text file. after that you can sort this list. – Bhargav Desai Jun 08 '20 at 05:47
  • I have one more question regarding above code. What if we want to join the lines which are starting with same integer – sri Jun 10 '20 at 22:48
  • first you have to read `int` from the lines. then find other lines with same integer. join all lines. after that , store `int` in list and next time if same int arrive go to next `int`. – Bhargav Desai Jun 12 '20 at 04:07
0

You can use write to save data to text file. Please see below:

with open('file.txt') as f:
  out = [x for x in f.read().split("\n") if x.strip() != ""] 
  for line1, line2 in list(zip(out, out[1:]))[::2]:
    line = " ".join([line1, line2])        
    print(line)
    with open('outfile.txt', 'a') as of:
      of.write(line + '\n')
Jinto Lonappan
  • 312
  • 2
  • 8
  • In this case, after executing outfile.txt is still an empty file. Any reason behind this? – sri Jun 05 '20 at 06:36
  • Lonappam thank you so much. What if we want to overwrite the data because every time we execute it will repeat. So, I just want the data only once even if run it multiple times. – sri Jun 05 '20 at 07:02
0

I think what you need is to group and iterate; once do that, you will able to write it to a file easily. Something like this:

data = """\
Jack loves dancing
Jack is a dancer
Tony likes candy
Tony ate candy\
"""

def grouped(iterable, n):
    return zip(*[iter(iterable)]*n)

for x, y in grouped(data.splitlines(), 2):
    print(x + " ; " + y)

Refer: Iterating over every two elements in a list

Nishant
  • 20,354
  • 18
  • 69
  • 101