[Python] Line Separator Python \r\n

Discussão em 'Python' iniciado por Stack, Maio 12, 2025.

  1. Stack

    Stack Membro Participativo

    We have an English-Latin dictionary in our hands, that is, a list of words in English and their translations into Latin (there may be several translations) in the form of a file with the following contents:

    apple - malum, pomum, popula
    fruit - baca, bacca, popum
    punishment - malum, multa


    It is necessary to write a script that reads a dictionary from files using the transmitted paths and creates a Latin-English dictionary from the dictionary. The result should be displayed on the screen.

    So for the line described above, the screen should display:

    baca - fruit
    bacca - fruit
    malum - apple, punishment
    multa - punishment
    pomum - apple
    popula - apple
    popum - fruit


    If different files contain different translations for the same words, multiple translations must be combined, leaving only unique words.

    And there are autotests.: There is a line there: student_output_lines = result.stdout.decode().strip() I did everything a long time ago, but the second day I can't get rid of \r

    When comparing the two outputs (mine == necessary), I get an error: E AssertionError: assert 'baca - fruit\r\nbacca - fruit\r\nmalum - apple, punishment\r\nmulta - punishment\r\npomum - apple\r\npopula - apple\r\npopum - fruit' == 'baca - fruit\nbacca - fruit\nmalum - apple, punishment\nmulta - punishment\npomum - apple\npopula - apple\npopum - fruit'

    My code:

    import sys
    for filename in sys.argv[1:]:
    with open(filename, 'r', encoding='utf-8') as f:
    res_dict = {}
    for s in f.readlines():
    cur_word = s.split()[0]
    translations = s.strip().replace(',', '').split()[2:]
    for i in translations:
    if i in res_dict:
    res_dict.append(cur_word)
    else:
    res_dict.setdefault(i, [cur_word])
    res = []
    for k, v in sorted(res_dict.items()):
    res.append(k + ' - ' + ', '.join(v))
    print('\n'.join(res).replace('\r\n', ''))


    The input files are in plain text format.txt:

    apple - malum, pomum, popula
    fruit - baca, bacca, popum
    punishment - malum, multa


    That is, I always have this disgusting \r, no matter what I do and replace and do everything I can. In the pycharm settings, I also changed the linear separator to /n, changed it both in the project (bottom right) and in settings -> code style -> linear separator. The problem always arises as soon as I add \n anywhere in the code. Help please!

    Continue reading...

Compartilhe esta Página