Цель состоит в разделении символа табуляции , который существует между двумя строками.
В частности, я хотел бы удалить символ табуляции между *Generic
и h_two
, который выделен желтым, как показано ниже
![enter image description here](https://i.stack.imgur.com/EzwrI.jpg)
the expected output as viewed using Microsoft Office application in a Show Paragraph Mark is a below'
![enter image description here](https://i.stack.imgur.com/XZnn1.jpg)
The file is from a txt format file.
One naive way is as
f_output.write(line.replace('*Generic \t \t', ','))
However, this did not work as intended.
So, there are two issues.
- The code below replace all the tab characters instead of only in between the Generic and h_two strings
- Как эффективно заменить только символы табуляции между подстроками?
Полный код для репликации этой проблемы:
import pandas as pd
fname = 'endnote_csv_help'
'''
Step 1) Create mock df and save to csv
'''
my_list = ['col_one', 'col_two', 'col_three']
combine_list = [{'h_one', 'h_two', 'h_three'}, my_list, my_list]
df = pd.DataFrame(combine_list)
df.to_csv(f'{fname}.csv', index=False, header=False)
'''
Step 2) Read the csv and convert to txt format
'''
df_shifted = pd.read_csv(f'{fname}.csv', header=None).shift(1, axis=0)
df_shifted.at[0, 0] = '*Generic'
df_shifted.fillna('').to_csv(f'{fname}.txt', sep='\t', index=False, header=False)
'''
Step 3) Read the txt and replace the tab character
'''
with open('endnote_csv_help.txt') as f_input, open('new_endnote_csv_help.txt', 'w') as f_output:
for line in f_input:
f_output.write(line.replace('*Generic \t \t', ','))
Примечание: ветка была немного обновлена после ответа @ Kuldeep.