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
I would use str.replace here:
wb['col'] = wb['col'].str.replace('^(\S+) (\S+)', '\1, \2,')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With