How to load whole values from a txt file? - Python

Asked

Viewed 76 times

1

I want to load a dictionary where the text file .txt contains information of the type String, but I want the values to be loaded Inteiro.

{'11322567498': '[0],[0]'}

Note that values are always being loaded as String.

Code I’m using to load the values into a dictionary:

def carregar_reservas(reserva):
    with open('reservas.txt') as doc:
        for line in doc:
            (cpf, name) = line.split()
            reserva[cpf] = name
  • 1

    First, I would like to warn you that although the CPF is a number, the ideal is to consider it as String, since there are CPF numbers that start with the character 0. So when making one Typecast of the kind String for Inteiro, it would be removed.

  • To resolve your question, you can simply perform the conversion of the type value String for the guy Inteiro. Learn more at: https://answall.com/questions/87584/como-converter-uma-vari%C3%A1vel-string-to-int

  • In this case, I tried to do this, only at the right value namely, '[0],[0]' only that ends up giving error. Valueerror: invalid literal for int() with base 10: '[0],[0]'

1 answer

2

@Userdel,

The variable name has characters that cannot be converted to number. In this case [, ] and ,

Ideal is to clear your variable before converting.

Using the command below, you will remove a number of unwanted characters.

name = name.translate({ord(c): "" for c in " !@#$%^&*()[]{};:./<>?\\|`~-=_+"})

Note that the comma was not part of the above command. I understand that it is a decimal divisor. So, at last, you would need to replace it by stitch with the replace

name = name.replace(",", ".")

Finally, make it whole with int(name) or float with float(name)

See the example below:

>>> name = "!#[10]$, [02]"
>>> name = name.translate({ord(c): "" for c in " !@#$%^&*()[]{};:./<>?\\|`~-=_+"})
>>> name
'10,02'
>>> name = name.replace(",", ".")
>>> name
'10.02'
>>> float(name)
10.02
>>>

I hope it helps

  • 1

    Apparently it works, but what if instead of removing all unwanted characters, regular expression is used Regex. I believe it would be a more viable option, due to the fact of not having to perform the treatment of character by character besides not letting pass any other special character not expected as º, ª, in addition to being simpler.

  • I agree that the regex helps in several problems. But sometimes it takes more time to create the expression than to resolve it in another way.

Browser other questions tagged

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