Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


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

like image 544
Z Azin Avatar asked Aug 10 '26 10:08

Z Azin


1 Answers

I would use str.replace here:

wb['col'] = wb['col'].str.replace('^(\S+) (\S+)', '\1, \2,')
like image 133
Tim Biegeleisen Avatar answered Aug 12 '26 23:08

Tim Biegeleisen