Insert commas after the first and second words in each line using Python?

Viewed 332


I have a .txt file and I need to convert it to CSV.
This is the code I'm using to convert the file:

import pandas as pd

wb = pd.read_csv('12.txt', encoding='utf-8', delimiter = '،', header = None)

wb.to_csv('12.csv',encoding='utf-8-sig', index = None)

The problem is, in each line, the first and second words need to be in separate cells, however they are not separated by commas :

This is an, example, to show, you
The second line, is, the, same
My file contains, thousands of, sentences

As shown in the example, only the first and second words of each line are supposed to be in separate cells (Other cells might contain more than one word!). How can I add commas ONLY after the first and second words in each line using Python?

Thanks

2 Answers

I would use str.replace here:

wb['col'] = wb['col'].str.replace('^(\S+) (\S+)', '\1, \2,')

If you are aiming for each word to be in a different cell, you could apply the following to each line:

line = "This is an, example, to, show, you"

split = line.split(",")

x = [item for sublist in [k.split(" ") for k in s] for item in sublist]
y = list(filter(lambda x: x != "", x))

output: ['This', 'is', 'an', 'example', 'to', 'show', 'you']
Related