#python #python_3x
У меня есть файл, в котором такое содержание:
CREATE TABLE some_name (
fv int,
sv int,
tv int)
CLUSTERED BY (fv,
sv,
tv)
SORTED BY (fv,
sv,
tv) INTO 2 BUCKETS;
-- more text afterwards
Мне нужно сделать так, чтобы скрипт стирал все слова от Clustered включительно до
Buckets включительно, но точку с запятой к примеру не стирал. Как можно реализовать
код? Мне предлагали такой:
start_word = "CLUSTERED"
end_word = "BUCKETS"
result_lines = []
with open(target_file, 'r') as f:
erasing = False
for line in f:
if not erasing and start_word in line:
// begin erasing lines
erasing = True
continue
if erasing and end_word in line:
// finished erasing lines
erasing = False
continue
if erasing:
// we are between the start and end of the section we want to erase
continue
else:
// either we haven't started erasing or we have already finished
result_lines.append(line)
print('\n'.join(result_lines))
Но он стирает точку с запятой и вообще всё, что на строках с Clustered и Buckets.
Результат должен быть приблизительно таким:
CREATE TABLE some_name (
fv int,
sv int,
tv int)
-- more text afterwards;
Ответы
Ответ 1
воспользйтесь регулярными выражениями: import re #text = """ #CREATE TABLE some_name ( #fv int, #sv int, #tv int) #CLUSTERED BY (fv, # sv, # tv) #SORTED BY (fv, # sv, # tv) INTO 2 BUCKETS; #-- more text afterwards #""" with open(target_file, 'r') as f: text = f.read() res = re.sub('CLUSTERED[\s\b\n\r]+[^;]*', '', text) print(res) CREATE TABLE some_name ( fv int, sv int, tv int) ; -- more text afterwardsОтвет 2
Пример через регулярку: import re text = """\ CREATE TABLE some_name ( fv int, sv int, tv int) CLUSTERED BY (fv, sv, tv) SORTED BY (fv, sv, tv) INTO 2 BUCKETS; -- more text afterwards """ new_text = re.sub('Clustered.+?Buckets;', ';', text, flags=re.I | re.DOTALL) print(new_text) Результат: CREATE TABLE some_name ( fv int, sv int, tv int) ; -- more text afterwards
Комментариев нет:
Отправить комментарий