File branch#2
Conversation
SidorinAnton
left a comment
There was a problem hiding this comment.
В целом неплохо, но кажется прям сильно переусложнила ))
| with open(input_fasta, 'r') as fasta_file: | ||
| fasta_lines = fasta_file.readlines() | ||
| with open('output_' + output_fasta + '.fasta', 'w') as output_fasta: | ||
| line_number = 0 | ||
| while line_number < len(fasta_lines)-1: | ||
| if fasta_lines[line_number][0] == '>': | ||
| output_fasta.write(fasta_lines[line_number]) | ||
| line_number += 1 | ||
| else: | ||
| count = line_number | ||
| string = '' | ||
| while count < len(fasta_lines) and fasta_lines[count][0] != '>': | ||
| string = string+fasta_lines[count].replace('\n', '') | ||
| count += 1 | ||
| output_fasta.write(string+'\n') | ||
| line_number = count |
There was a problem hiding this comment.
-
readlinesне оч хорошо, т.к. если файл очень большой, то можем упасть с ошибкой ))
Лучше делать итерацию по строкам -
Чет ты прям оч сильно переусложнила ))
Можно ж что-нибудь в духе:
with open(INPUT) as inp_fa, open(OUTPUT, "w") as opt_fa:
for line in inp_fa:
if line.startswith(">"):
opt_fa.write("\n") # Можно аккуратнее сделать проверку на первую строку, тогда не будет \n вначале
opt_fa.write(line)
continue
opt_fa.write(line.strip())| :return: a fasta file with shifted sequence | ||
| """ | ||
|
|
||
| if os.path.isfile(input_fasta) == False: |
There was a problem hiding this comment.
Зачем? ))
Не нужно делать False == False, если это само по себе уже bool.
То есть буквально if not ...isfile
| if os.path.isfile(input_fasta) == False: | ||
| print('The path does not exist!') | ||
| with open(input_fasta, 'r') as fasta_file: | ||
| lines = fasta_file.readlines() |
There was a problem hiding this comment.
Не оч хорошо, т.к. если файл очень большой, то можем упасть с ошибкой ))
Лучше делать итерацию по строкам
| line = line | ||
| if shift > 0: | ||
| first_part_line = line[:shift] | ||
| last_part_line = line[shift+1:] | ||
| shifting_nucleotide = line[shift] | ||
| result_sequence = shifting_nucleotide + first_part_line + last_part_line | ||
| elif shift == -1: | ||
| shifting_nucleotide = line[shift] | ||
| first_part_line = line[:shift] | ||
| result_sequence = shifting_nucleotide + first_part_line |
There was a problem hiding this comment.
Чет тоже сильно переусложнила ... Это же по сути просто line[shift:] + line[:shift]. В питоне есть отрицательная индексация. Вот если из примера:
inp = "ATCG"
print(inp[2:] + inp[:2]) # CGAT (второй нуклеотид справа стал первым)
print(inp[-1:] + inp[:-1]) # GATC (первый нуклеотид слева стал первым)| import modules.fastaq_tool as fqt | ||
| import modules.dna_rna_tool as drt | ||
| import modules.protein_tool as prt |
There was a problem hiding this comment.
Не надо ))
Просто импортируй нужные функции, константы, классы итд
| result = 100 * gc / len(seq[0]) | ||
| return gc_bounds[0] <= result <= gc_bounds[1] | ||
|
|
||
| def length_count(seq: tuple, length_bounds: int or tuple = (0, 2 ** 32)) \ |
There was a problem hiding this comment.
А зачем здесь передавать в seq -- tuple, если можно сразу нужную строку ))
| def check_dir() -> bool: | ||
| """ | ||
| Checks if directory fastq_filtrator_resuls exists. If it exists, the | ||
| function returns True, else it creates the directory in the working | ||
| directore | ||
| "fastq_filtrator_resuls" and returns True. | ||
| :return: True always | ||
| """ | ||
| if os.path.exists('fastq_filtrator_resuls'): | ||
| return True | ||
| else: | ||
| os.mkdir('fastq_filtrator_resuls') | ||
| return True |
There was a problem hiding this comment.
Ты, используя эту функцию, как бы ожидаешь узнать, есть папка или нету.
А у тебя получается, если есть -- норм. Если нет -- сча сделаю ))
Если хочется так, тогда это не check ))
Ну и тож не оч понятно, а зачем всегда возвращать True ))
| else: | ||
| if method not in ['convert_aa_coding', | ||
| 'from_proteins_seqs_to_rna', | ||
| 'isoelectric_point_determination', | ||
| 'calc_protein_molecular_weight', | ||
| 'back_translate']: | ||
| raise ValueError(method, ' is not a valid method.') | ||
| else: | ||
| seqs_list = list(args) | ||
| for i, seq in enumerate(seqs_list): | ||
| if is_one_letter(seq): | ||
| print(f'Warning! Function {method}() needs ' | ||
| '3-letter encoded sequences. Your sequence ' | ||
| 'will be mutated to a 3-letter encoding.') | ||
| seqs_list[i] = recode(seq) | ||
| print(seq, ' sequence has been mutated into: ', | ||
| seqs_list[i]) | ||
| seq_on = None | ||
| return seqs_list, seq_on |
There was a problem hiding this comment.
Посмотри, какая большая вложенность из-за else ))
Если ты попала в raise, то дальше код не пойдет. То есть ты могла бы сделать в духе:
if ...:
raise
if ...:
raise
...| file.write(out_data[key][0] + '\n') | ||
| file.write('+' + key) | ||
| file.write(out_data[key][1] + '\n') | ||
| file.write('\n') |
| file.write('+' + key) | ||
| file.write(out_data[key][1] + '\n') | ||
| file.write('\n') | ||
| return file |
No description provided.