0
$\begingroup$

I am playing with a .txt file in python for EDA and I want to seperate the lines from this fashion:

Corona Virus = Justin Piper

COVID19 = Piper, Justin
Fed Paper Says Companies May Automate More Jobs During Pandemic https://t.co/SUqrMfpNJY

Donate the money 
Might put food on plate 
And smile on face 😊

to this fashion:

[['Corona Virus = Justin Piper'],['COVID19 = Piper, Justin
Fed Paper Says Companies May Automate More Jobs During Pandemic https://t.co/SUqrMfpNJY'],['Donate the money 
Might put food on plate 
And smile on face 😊']]

I tried .split('\t') but it is taking each line as a new row.

$\endgroup$
1
$\begingroup$

You can read the file line by line, discard blank lines, and wrap the lines that are left by a list to get the same as your desired result

with open(file_name, 'r') as f:
    print([[x.strip()] for x in f.readlines() if x.strip() != ''])

By doing [x.strip()] you clear the whitespace at the beginning and end of the file and then wrap it in a list, and the condition x.strip() != '' makes sure that the line actually contains content and is not just a blank line.

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.