Coder Social home page Coder Social logo

matheuscas / pycpfcnpj Goto Github PK

View Code? Open in Web Editor NEW
142.0 8.0 44.0 150 KB

Python module for brazilian register numbers for persons (CPF) and companies (CNPJ).

License: MIT License

Python 100.00%
python cnpj cpf python-2 python-library validation generation python-3

pycpfcnpj's Introduction

Pycpfcnpj

Description

Python module for brazilian register numbers for persons (CPF) and companies (CNPJ). If want this validation in your web application, please check my tiny web component that does exactly that. ;)

Testing codecov PyPI version Python versions

Related projects

  • Pycnpj-crawler: Python module that crawls data for a given CNPJ on the government website of each state (please check the supported states).

How to install

Now you can install this module with pip! Yeah! :D

pip install pycpfcnpj

Quick Start

To use pycpfcnpj is simples like as every python module should be!

from pycpfcnpj import cpfcnpj
cpf_number = '11144477735'
masked_cpf_number = '111.444.777-35'
cnpj_number = '11444777000161'
masked_cnpj_number = '11.444.777/0001-61'

print(cpfcnpj.validate(cpf_number))
print(cpfcnpj.validate(masked_cpf_number))
print(cpfcnpj.validate(cnpj_number))
print(cpfcnpj.validate(masked_cnpj_number))

Expected output:
>>>True
>>>True
>>>True
>>>True

Simple like that. =)

You can use, as well, the cpf and cnpj packages. The cpfcnpj is like a Facade to the other modules. Make yourself confortable.

Oh, fork and contribute either if you want to.

Obs.: There is no dependencies.

Oh, and before I forget, you can generate, only and only for test purposes, a CPF or CNPJ number using the 'gen' module. Easy like above:

from pycpfcnpj import gen
gen.cpf()
gen.cnpj()

Expected output:
>>> 49384063495
>>> 20788274885880

Also, you can generate CPF or CǸPJ with punctuation marks. :)

from pycpfcnpj import gen
gen.cpf_with_punctuation()
gen.cnpj_with_punctuation()

Expected output:
>>> 048.891.866-97
>>> 63.212.638/0361-35

Have fun!

In portuguese:

Módulo python para validar números de CPF e CNPJ.

Como instalar:

Agora você pode instalar o pycpfcnpj usando o pip!\m/

pip install pycpfcnpj

Projetos relacionados

Como usar

from pycpfcnpj import cpfcnpj
cpf_number = '11144477735'
masked_cpf_number = '111.444.777-35'
cnpj_number = '11444777000161'
masked_cnpj_number = '11.444.777/0001-61'

print(cpfcnpj.validate(cpf_number))
print(cpfcnpj.validate(masked_cpf_number))
print(cpfcnpj.validate(cnpj_number))
print(cpfcnpj.validate(masked_cnpj_number))

Expected output:
>>>True
>>>True
>>>True
>>>True

Simples assim! Você também pode usar os pacotes internos que tratam em separado os números de CPF e CNPJ. O módulo 'cpfcnpj' é um tipo de interface para os módulos mais específicos e se encarrega de saber quando você está passando um CPF ou um CNPJ.

Fique à vontade em contribuir com o projeto ou da maneira que quiser. Ah, sim: pure python (sem dependências ;) ).

Ah, e antes que eu me esqueça, você pode gerar, só e apenas somente para fins de teste, um número de CPF ou CNPJ utilizando o módulo 'gen'. Fácil como acima:

from pycpfcnpj import gen
gen.cpf()
gen.cnpj()

Expected output:
>>> 49384063495
>>> 20788274885880

E você também pode gerar CPF ou CNPJ com pontuação :)

from pycpfcnpj import gen
gen.cpf_with_punctuation()
gen.cnpj_with_punctuation()

Expected output:
>>> 048.891.866-97
>>> 63.212.638/0361-35

Divirta-se!

Changelog

1.8

  • Dropped travis and python versions under 3.8

1.7.2

  • Use poetry to handle dev/test dependencies, building and publishing

1.7.1

  • Fix for cpf/cnpjs containing special characters.

1.7.0

  • Invalidates cpf/cnpjs containing non-numeric characters and spaces.

1.6.0

  • Remove python 2.7 support
  • Add python 3.8 support

1.1

  • Handles CPF and CNPJ numbers with punctuation marks.

1.2

  • Use sys rather than six to check python's version and keeps this project 100% free of dependencies.

1.3

  • Generate CPF and CNPJ numbers with punctuation marks.

1.4

  • Adding support to unicode values.

1.5

  • Better CPF and CNPJ generation

1.5.1

  • Use regex to remove punctuation

Log de mudanças

1,8

  • Travis fora e versões do Python abaixo de 3.8 não são mais suportadas

1.7.2

  • Use Poetry para lidar com dependências de desenvolvimento/teste, construção e publicação

1.7.1

  • Correção para cpf/cnpjs que contém caracteres especials.

1.7.0

  • Invalida cpf/cnpjs que contém caracteres não numéricos e espaços.

1.6.0

  • Remove suporte para python 2.7
  • Adiciona suporte para python 3.8

1.1

  • Trata números de CPF e CPNJ com sinais de pontuação

1.2

  • Uso do sys em vez do six para verificar a versão do Python e evitando o uso de libs terceiras

1.3

  • Gera números de CPF e CNPJ com pontuação.

1.4

  • Suporte a unicode.

1.5

  • Geração de CPF e CNPJ mais eficiente.

1.5.1

  • Regex para remover a pontuação.

pycpfcnpj's People

Contributors

asagalo avatar beatrizuezu avatar bruno-fs avatar cshlopes avatar dependabot[bot] avatar isabelapnt avatar jeffersonkr avatar matheuscas avatar paulohrpinheiro avatar rodfersou avatar rubens-brandao avatar sergiors avatar tirkarthi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pycpfcnpj's Issues

Add pre-commit hooks (Adicione o pre-commit hook)

Back in the days, black didn't exist (or it wasn't very known to me) and the code is not formatted. A good thing to do here would be to add the pre-commit hooks and add things like black, isort, and flake8.

Antigamente, o black não existia (ou não era muito conhecido por mim) e o código não está formatado. Uma boa coisa a fazer aqui seria adicionar os pre-commit hooks e adicionar coisas como black, isort e flake8.

Add typing (Adicione typings)

Since the "new" hype is typing all the things, let's enjoy this wave and type this small (but useful) project. It could help the auto-completion in other projects and IDEs.

Já que o "novo" hype is adicionar tipos em todas as coisas, vamos aproveitar essa onda e adicionar tipos nesse pequeno (mas útil) projeto. Poderia ajudar a auto-completar em outros projetos e IDEs

Pip Install Doesn't have Six Dependency

Hello how are you guys?
I've installed this library and I notice that it requires six library. Looks like this lib doesn't have it within its dependencies.
As soon as I arrive home I'll make a pull request adding it.

Thanks

Use github actions instead of Travis (use github action em vez do Travis)

I have nothing against Travis, but since we're in GitHub, let's use "native" stuff from it.
Tip.: First make the action runs in your branch. After that, change to run in master.

Não tenho nada contra Travis, mas como estamos no GitHub, vamos usar coisas "nativas" dele.
Dica: Primeiro faça com que a ação seja executada no seu branch. Depois disso, mude para rodar no master.

Como aplicar o validador em um df?

Olá, parabéns pelo trabalho.
Estou tentando aplicar seu validador em uma lista de CNPJs e CPFs e um DF (vieram de um XLSX).
No entanto quando tento o código abaixo apresenta o erro: AttributeError: 'Series' object has no attribute 'translate'

df['Valida'] = cpfcnpj.validate(df['CNPJ'])

conseguiria me ajudar?

Adicionar uma validação extra no clear punctuation

Casos aonde funciona pois temos as condicionais
image

>>> from pycpfcnpj import cpfcnpj
>>> cpfcnpj.validate('+123')
False

Casos que quebra o código pois ele da match em umas da condicionais

>>> cpfcnpj.validate("+5575999769162")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jkwak/.local/lib/python3.8/site-packages/pycpfcnpj/cpfcnpj.py", line 24, in validate
    return cnpj.validate(clean_number)
  File "/home/jkwak/.local/lib/python3.8/site-packages/pycpfcnpj/cnpj.py", line 28, in validate
    if (first_digit == calc.calculate_first_digit(first_part) and
  File "/home/jkwak/.local/lib/python3.8/site-packages/pycpfcnpj/calculation.py", line 28, in calculate_first_digit
    sum = sum + int(number[i]) * weights[i]
ValueError: invalid literal for int() with base 10: '+'

Precisamos validar antes de ir para o validate se existes esses caracteres especiais e retornar Falso caso exista.

Deprecation warning due to invalid escape sequences

Deprecation warning due to invalid escape sequences. Using raw strings or escaping them again helps in resolving this.

find . -iname '*py' | grep -Ev 'setup|rdf4|tool' | xargs -P4 -I{} python3.8 -Wall -m py_compile {}
./pycpfcnpj/compatible.py:6: DeprecationWarning: invalid escape sequence \D
  return re.sub('\D', '', str(document))

Update tests (atualizar os tests)

It seems that pytest version is broken and the tests are using unittests. Since this is an old (but very dear for me) project, we should update the tests to use a more function-based approach.

Parece que a versão do pytest está quebrada e os testes estão usando unittests. Como este é um projeto antigo (mas muito querido para mim), devemos atualizar os testes para usar uma abordagem mais baseada em funções.

Generates numbers with punctuation marks

After the release 1.1, that handles input numbers with punctuation marks, it would be also nice generate numbers with correct punctuation marks to each type of number, CPF and CNPJ.

Refactor tests

pyunit are not clean and concise. Pytest would be a better choice.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.