Sort a. csv file from the numeric column

Asked

Viewed 1,083 times

1

I have the following file:

es;548
la;1832
primera;35
vez;107
que;2598
hago;15
un;878
pedido;642
y;1713
creo;83
ha;207
funcionado;1
muy;371
bien;257
los;1054
precios;88
fuesen;11

And I’d like to sort it from the numerical column, from the largest to the smallest. I tried that, but it’s not working:

with open ("FREQ.csv", "r") as f:
    dados = f.read()
    colunas = dados.split(";")

    print (sorted (dados[1], key = int, reverse = True))
  • 1

    A CSV file is a file that has a fixed number of columns and multiple rows that follow the same structure. In your case it seems to be just a text file with only one line that has data separated by a semicolon. You can ask the question an example of the correct output of this file line?

  • 1

    That’s right. He placed only one line of the CSV file.

  • 1

    But what you meant by 'is not working', which, in fact, happens?

  • I have this message: /usr/bin/python3.5 /home/Janaina/Bureau/Lexique/Python/sort_freq.py Traceback (Most recent call last): File "/home/Janaina/Bureau/Lexique/Python/sort_freq.py", line 7, in <module> print (data[1], key = int, Reverse = True)) Valueerror: invalid literal for int() with base 10: ’s' Process finished with Exit code 1

  • @Pagotti I have exactly one CSV file (I didn’t create it), the problem is I can’t put it here the way it is (two columns).

  • @Pitanga you don’t need to put the exact file in the question. Just update the question with an example of data (can be 2 lines from the file) and an example of how you expect the output to be. The way you’re putting it is confusing.

Show 1 more comment

2 answers

2

Use the module csv (https://docs.python.org/3.6/library/csv.html)

I performed the tests using python3.

import csv


with open ("freq.csv", "r") as f:
    dados = csv.reader(f, delimiter=";")
    # Com o arquivo lido pelo módulo csv é possível convertê-lo em uma lista
    lista = list(dados)
    # Ordenação da lista gerada considerando o segundo elemento em ordem decrescente.
    lista_ordenada = sorted (lista, key = lambda dado: int(dado[1]), reverse = True)

    for x in lista_ordenada:
      print(x)

1

A simpler way to do this is to separate all lines of csv \n and after that separate all csv columns ;. After aggregating all rows and columns in a list just give a Sort in the expected column, you can use the lambda and "customize" the sort method, follows:

colunas = list([dado.strip().split(";") for dado in dados.strip().split("\n")])
colunas.sort(key=lambda linha: int(linha[1]), reverse=True)
print(colunas)

or rather than give the colunas.sort... you can use the sorted:

print(sorted(colunas, key=lambda linha: int(linha[1]), reverse=True))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.