Extrair Números de um Arquivo de Texto

PythonBeginner
Pratique Agora

Introdução

Neste projeto, você aprenderá como extrair números maiores que 5 de um arquivo de texto e imprimi-los.

👀 Visualização

$ python FindDigits.py
876

🎯 Tarefas

Neste projeto, você aprenderá:

  • Como abrir um arquivo de texto e ler seu conteúdo
  • Como extrair números específicos de uma string
  • Como concatenar os números extraídos em uma nova string
  • Como imprimir os números extraídos

🏆 Conquistas

Após concluir este projeto, você será capaz de:

  • Manipular strings e extrair dados específicos delas
  • Escrever um script Python para automatizar uma tarefa simples de processamento de dados
  • Aplicar seu conhecimento de manipulação de arquivos e operações de string em Python

Abrir o Arquivo String.txt e Ler a String

Nesta etapa, você aprenderá como abrir o arquivo String.txt e ler a string.

  1. Abra seu editor de texto e crie um novo arquivo chamado FindDigits.py no diretório /home/labex/project.
cd /home/labex/project
touch FindDigits.py
  1. No arquivo FindDigits.py, use a função open para abrir o arquivo String.txt no mesmo diretório e ler a string.
## Open the String.txt file in the same directory and read the string
with open("String.txt", "r") as f:
    string = f.read()

A instrução with é usada para garantir que o arquivo seja fechado corretamente após a leitura ser concluída, mesmo que uma exceção seja levantada.

✨ Verificar Solução e Praticar

Extrair os Números Maiores que 5 da String

Nesta etapa, você aprenderá como extrair os números maiores que 5 da string e concatená-los em uma nova string.

  1. Inicialize uma string vazia para armazenar os números extraídos.
## Initialize an empty string to store the extracted numbers
numbers = ""
  1. Itere por cada caractere na string e verifique se é um dígito e maior que 5. Se for, adicione-o à string numbers.
## Loop through each character in the string
for char in string:
    ## If the character is a digit and greater than 5
    if char.isdigit() and int(char) > 5:
        ## Append it to the numbers string
        numbers += char

O método isdigit() verifica se o caractere é um dígito, e int(char) converte o caractere em um inteiro para verificar se é maior que 5.

✨ Verificar Solução e Praticar

Imprimir os Números Extraídos

Nesta etapa, você aprenderá como imprimir os números extraídos.

  1. Imprima a string numbers.
## Print out the numbers string
print(numbers)

O arquivo FindDigits.py final deve ser semelhante a este:

## Open the String.txt file in the same directory and read the string
with open("String.txt", "r") as f:
    string = f.read()

## Initialize an empty string to store the extracted numbers
numbers = ""

## Loop through each character in the string
for char in string:
    ## If the character is a digit and greater than 5
    if char.isdigit() and int(char) > 5:
        ## Append it to the numbers string
        numbers += char

## Print out the numbers string
print(numbers)

Você concluiu o projeto. Execute o arquivo FindDigits.py para ver a saída.

$ python FindDigits.py
876
✨ Verificar Solução e Praticar

Resumo

Parabéns! Você concluiu este projeto. Você pode praticar mais laboratórios no LabEx para aprimorar suas habilidades.