AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 77496177
Accepted
CountryBoy_71
CountryBoy_71
Asked: 2023-11-16 23:44:03 +0800 CST2023-11-16 23:44:03 +0800 CST 2023-11-16 23:44:03 +0800 CST

Extração de dados de arquivo txt bagunçado - Power Query

  • 772

Bom dia...Recebi um conjunto de dados muito bagunçado para limpar...meu primeiro pensamento foi PQ. Abaixo está um trecho das mais de 10k linhas no .txtarquivo real, ele simplesmente se repete para cada usuário ('C:'), separado pela extensão ----------. Para começar, a lista é a informação que, no momento, preciso extrair. Na primeira importação para PQ, é uma coluna; guia separada.

  1. C:
  2. Nome do assinante
  3. Cobranças Atuais (todos os campos)
  4. Outras cobranças e crédito
  5. Outras taxas
  6. Impostos
"Company-Name." Client No:  "5780859"
" " Purchase Order No:
Invoice Date:   30-Sep-23   Unique Invoice No:  "123456789"
"12345 Main Street"
"City AB"
"T4A 1B7"

"Account Number 1234567"
"-------------------------------------------------------------------------------"
"REPORT - INDIVIDUAL DETAILS"

--------------
"C:"    "1234567890"
"Subscriber Name:"  "NAME.NAME SPARE"
"Additional line user name:"    ""
"Sublevel:" " "
"Sublevel:" ""
"Reference 1:"  ""
"Reference 2:"  ""

"Handset Transparency"
"Number/Device Information" ""
"Starting Balance"  $0.00
"Last Month's Balance"  $0.00
"Current Balance"   $0.00
"Monthly Credit"    $0.00
"Monthly Balance Adjust"    $0.00


"CURRENT CHARGES"
"Monthly Service Plan"  $40.00
"Additional Local Airtime"  $0.00
"Long Distance Charges" $22.40
"Roaming Charges"   $0.00
"Total Taxes:"  $7.49
"Total Current Charges:"    $69.89

"MONTHLY SERVICE PLAN"  01-Oct-23 to 31-Oct-23
"Service Plan Name" "Total"
"Business SharePro 5GB Q1 offer (01-Oct-23 to 31-Oct-23)"   $40.00
"Total Monthly Service Plan Charges"    $40.00

"ADDITIONAL LOCAL AIRTIME"
"Service"   "Total Airtime" "Free Airtime"  "Included Airtime"  "Chargeable Airtime"    "Total"
"Phone (minutes)"   28:00   0:00    28:00   0:00    $0.00
"Total Additional Local Airtime Charges"    $0.00

"LONG DISTANCE CHARGES"
"Service"   "Total LD Minutes"  "Free LD Minutes"   "Included LD Minutes"   "Chargeable LD Minutes" "Total"
"Domestic Phone"    28:00   0:00    0:00    28:00   $22.40
"Total Long Distance Charges"   $22.40

"ROAMING"
"Service"   "Roaming Minutes"   "Roaming Charges"   "Roaming LD Minutes"    "Roaming LD Charges"    "Roaming Surcharge" "Total"
"Total Roaming Charges" $0.00

"DO MORE DATA SERVICES"
"Service"   "Total Events"  "Event Type"    "Total"
"Total Do More Data Services Charges"   $0.00

"DO MORE VOICE SERVICES"
"Service"   "Total Events"  "Event Type"    "Total"
"Total Do More Voice Services Charges"  $0.00

"PAGER SERVICES"
"Service"   "Total Messages"    "Included Messages" "Chargeable Messages"   "Total"
"Total Pager Charges"   $0.00

"VALUE-ADDED SERVICES"  01-Oct-23 to 31-Oct-23
"Service"   "Total"
"Can - Can/US LD $0.80/min (01-Oct-23 to 31-Oct-23)"    $0.00
"Easy Roam INTL - $16/day Business (01-Oct-23 to 31-Oct-23)"    $0.00
"Easy Roam US - $14/day Business (01-Oct-23 to 31-Oct-23)"  $0.00
"UL Can - Can LD min (01-Oct-23 to 31-Oct-23)"  $0.00
"UL domestic SMS / MMS (01-Oct-23 to 31-Oct-23)"    $0.00
"Visual Voicemail (01-Oct-23 to 31-Oct-23)" $0.00
"Total Value Added Service Charges" $0.00

"OTHER CHARGES AND CREDIT"
"Charge or Credit"  "Total"
"Total Other Charges and Credits"   $0.00

"OTHER FEES"
"Service"   "Total"
"Other Fees"    $0.00

"TAXES"
""  "Total"
"GST"   $3.12
"PST - BC"  $4.37
"Total Taxes"   $7.49

Depois de muita brincadeira, usei as seguintes etapas;

  1. Linhas filtradas (linhas superiores removidas)
  2. Adicionada uma coluna de índice e, em seguida, uma coluna condicional para retornar o valor de '-----', que então 'preenchi'.
  3. Filtrado novamente para manter apenas as linhas realmente necessárias
  4. Divida a coluna única por delimitador (tab), pois é assim que o arquivo '.txt' é apresentado
  5. Removida a (o que eventualmente será) coluna de cabeçalhos, pois estava mexendo comigo.
  6. Agrupou as linhas da coluna condicional e fez uma busca detalhada para obter uma lista
  7. A etapa final foi usar 'Table.Combine' da lista.

Então, agora tenho as linhas exibidas como deveriam, mas aqui está o próximo problema. Nem todo usuário (C:) tem o mesmo número de linhas (cobranças), então os dados se espalham por muitas colunas que não estão mais onde deveriam estar.

Existe alguma maneira de resolver isso? Algo assim é mais adequado para Python?

powerquery
  • 1 1 respostas
  • 26 Views

1 respostas

  • Voted
  1. Best Answer
    Sam Nseir
    2023-11-17T00:28:11+08:002023-11-17T00:28:11+08:00

    Veja se isso ajuda você a seguir em frente...

    let
        Source = Csv.Document(File.Contents("C:\5780859.txt"),[Delimiter="#(tab)", Columns=2, Encoding=1252, QuoteStyle=QuoteStyle.None]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}, {"Column2", type text}}),
        #"Added Custom" = Table.AddColumn(#"Changed Type", "Customer", each if [Column1] = "C:" then [Column2] else null),
        #"Filled Down" = Table.FillDown(#"Added Custom",{"Customer"}),
        #"Filtered Rows" = Table.SelectRows(#"Filled Down", each [Customer] <> null and [Customer] <> ""),
        #"Filtered Rows1" = Table.SelectRows(#"Filtered Rows", each [Column1] <> null and [Column1] <> ""),
        #"Added Custom1" = Table.AddColumn(#"Filtered Rows1", "Section", each if [Column1] = Text.Upper([Column1]) then [Column1] else null),
        #"Filled Down1" = Table.FillDown(#"Added Custom1",{"Section"}),
        #"Filtered Rows2" = Table.SelectRows(#"Filled Down1", each ([Section] = "C:" or [Section] = "CURRENT CHARGES" or [Section] = "OTHER CHARGES AND CREDIT" or [Section] = "OTHER FEES" or [Section] = "TAXES")),
        #"Filtered Rows3" = Table.SelectRows(#"Filtered Rows2", each ([Column2] <> null and [Column2] <> "") and ([Column1] = "C:" or [Column1] = "Subscriber Name:" or [Section] <> "C:"))
    in
        #"Filtered Rows3"
    

    insira a descrição da imagem aqui

    • 2

relate perguntas

  • Combine o conteúdo das colunas com a lista dinâmica na consulta avançada

  • Corte os últimos 3 caracteres da string com uma condição usando o Power Query no Excel

  • Modifique este código do Power Query para ler pastas em vez de um único arquivo

  • Power Query - Transpondo várias linhas em colunas singulares

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    destaque o código em HTML usando <font color="#xxx">

    • 2 respostas
  • Marko Smith

    Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}?

    • 1 respostas
  • Marko Smith

    Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)?

    • 2 respostas
  • Marko Smith

    Por que as compreensões de lista criam uma função internamente?

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 respostas
  • Marko Smith

    Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)?

    • 4 respostas
  • Marko Smith

    Por que o construtor de uma variável global não é chamado em uma biblioteca?

    • 1 respostas
  • Marko Smith

    Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto?

    • 1 respostas
  • Marko Smith

    Somente operações bit a bit para std::byte em C++ 17?

    • 1 respostas
  • Martin Hope
    fbrereto Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi Por que as compreensões de lista criam uma função internamente? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A formato fmt %H:%M:%S sem decimais 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python std::views::filter do C++20 não filtrando a visualização corretamente 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa Por que o construtor de uma variável global não é chamado em uma biblioteca? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev Por que os compiladores perdem a vetorização aqui? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan Somente operações bit a bit para std::byte em C++ 17? 2023-08-17 17:13:58 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve