輸入(2列):
col1 , col2
David, 100
"Ronald
Sr, Ron , Ram" , 200
Harry
potter
jr" , 200
Prof.
Snape" , 100
注意:Harry and Prof. 沒有起始引號
輸出(2 列)
col1 | col2
David | 100
Ronald Sr , Ron , Ram| 200
Harry potter jr| 200
Prof. Snape| 100
我試過什么(PySpark)?
df = spark.read.format("csv").option("header",True).option("multiLine",True).option("escape","\'")
問題 上面的代碼在多行同時具有開始和結束雙引號的情況下運行良好(例如:以 Ronald 開頭的行)
但它不適用于我們只有結束引號但沒有開始引號的行(如 Harry 和 Prof)
即使我們在 Harry 和 Prof 中添加開頭引號,也可以解決問題
歡迎任何使用 Pyspark、Python 或 Shell 等的想法!
uj5u.com熱心網友回復:
僅基于提供的小樣本:
- 洗掉所有雙引號
- 有兩個逗號分隔的欄位;第一個欄位是一個字串,第二個欄位是一個數字
- 第一個欄位可能包含逗號,并且可能跨多行
- 用豎線 (
|)替換逗號分隔符 - OP 的預期輸出與新插入管道 ( ) 之前的間距不一致
|;有時洗掉一個空格,有時插入一個空格;現在我們不用擔心間距
一個awk想法:
awk -F, '
{ gsub(/"/,"") } # remove double quotes
FNR==1 || # if 1st line or last field is a number then ...
($NF 0)==$NF { print prev gensub(FS,"|",(NF-1)) # print any previous line(s) data plus current line, replacing last comma with a pipe
prev="" # clear previous line(s) data
next # skip to next line of input
}
{ prev= prev $0 " " } # if we get here then this is a broken line so save contents for later printing
' sample.csv
這會產生:
col1 | col2
David| 100
Ronald Sr, Ron , Ram | 200
Harry potter jr | 200
Prof. Snape | 100
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477080.html
