Как эффективно удалить символ табуляции из файла формата txt с помощью Python - PullRequest
1 голос
/ 09 июля 2020

Цель состоит в разделении символа табуляции , который существует между двумя строками.

В частности, я хотел бы удалить символ табуляции между *Generic и h_two, который выделен желтым, как показано ниже

enter image description here

the expected output as viewed using Microsoft Office application in a Show Paragraph Mark is a below'

enter image description here

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.

  1. The code below replace all the tab characters instead of only in between the Generic and h_two strings
  1. Как эффективно заменить только символы табуляции между подстроками?

Полный код для репликации этой проблемы:

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.

Ответы [ 3 ]

1 голос
/ 09 июля 2020

Вход: endnote_csv_help.txt

*Generic        
h_one   h_three h_two
col_one col_two col_three

Выход: new_endnote_csv_help.txt

*Generic,,
h_one,h_three,h_two
col_one,col_two,col_three

Чтение строки из входа и замена табуляции запись ее в выход

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('\t', ','))
0 голосов
/ 09 июля 2020

Как видно, между * Generi c и h_two есть два символа Tab.

Следовательно, это можно просто заменить на

replace('\t\t', '')

Полный код затем, как показано ниже

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('\t\t', ''))

Обратите внимание, что не должно быть пробелов между символом табуляции символов \t\t.

Благодаря предложению @Kuldeep, он дает основную подсказку. В результате его комментарий будет принят как ответ

0 голосов
/ 09 июля 2020

за другой ответ - ваша ошибка связана с тем, что вы читаете из файла, который вы открыли для записи. Если вы хотите заменить несколько экземпляров вкладки пустым, используйте reg expr. Это выражение соответствует 2 или более последовательным вкладкам с пустой строкой

import re
data = '*Generic\t\t\nh_three\th_one\th_two\ncol_one\tcol_two\tcol_three\n'
re.sub("([\t][\t]+)", "", data)

вывод

'*Generic\nh_three\th_one\th_two\ncol_one\tcol_two\tcol_three\n'

для удаления исключения, чтение из файла, который открыт для чтения и записи в файл, открытый для записи.

import pandas as pd
import re

fname = 'endnote_csv_help'
'''
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)

'''
# 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)

'''
Read the txt and replace the tab character
'''

with open(f'{fname}.txt', 'r') as file:
    data = re.sub("([\t][\t]+)", "", file.read())
with open(f'{fname}.txt', 'w') as file:
    file.write(data)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...