簡體   English   中英

將格式不正確的CSV讀取到熊貓中-未轉義的引號

[英]reading improperly formatted CSV into pandas - unescaped quotes

我繼承了幾百個CSV,我想將它們導入到pandas數據框中。 它們的格式如下:

username;date;retweets;favorites;text;geo;mentions;hashtags;id;permalink
;2011-03-02 11:04;0;0;"ICYMI: "What you have is 87 people who have common goals of working for [the] next generation; that’s why our...";;;;"42993734165594112";https://twitter.com/AustinScottGA08/status/42993734165594112
;2014-02-25 10:38;3;0;"Will be asking tough questions of #IRS at 2/26 FSGG hearing; supporting bills to make agency more accountable.";;;#IRS;"438352361812426752";https://twitter.com/AnderCrenshaw/status/438352361812426752
;2017-06-14 12:39;4;6;"Thank you to the brave men and women who have answered the call to defend our great nation. Happy 242nd Birthday @USArmy ! #ArmyBDay pic.twitter.com/brBYCOLBJZ";;@USArmy;#ArmyBDay;"875045042758369281";https://twitter.com/AustinScottGA08/status/875045042758369281

要將其放入熊貓數據框,我嘗試:

tweets = pd.read_csv(file, header=0, sep=';', parse_dates = True)

並得到此錯誤:

ParserError: Error tokenizing data. C error: Expected 10 fields in line 1, saw 11

我認為那是因為字段內有一個不轉義的引號

ICYMI:“您擁有87位共同為下一代工作的目標的人;這就是我們...

所以,我嘗試

tweets = pd.read_csv(file, header=0, sep=';', parse_dates = True, quoting=csv.QUOTE_NONE)

並得到一個新的錯誤(我認為是因為該字段中有;):

在2/26 FSGG聽證會上將問#IRS的棘手問題; 支持法案,使代理機構更加負責。 http://tinyurl.com/n8ozeg5

ParserError: Error tokenizing data. C error: Expected 10 fields in line 2, saw 11

我無法重新生成這些CSV文件。 我想知道的是,如何預處理/修復它們,以使其正確格式化(即,字段中的轉義引號)? 或者,是否有一種方法即使使用未轉義的引號也可以直接將它們讀入數據框?

在讀熊貓之前,我會先清理數據。 這是我對您當前問題的解決方案。

編輯:
這將取代; 雙引號內(基於答案)

o = open("fileOut.csv", 'w')
with open("fileIn.txt") as f:
   for lines in f:
      o.write(re.sub('\"[^]]*\"', lambda x:x.group(0).replace(';',''), lines))
o.close()

原版的:

o = open("fileOut.csv", 'w')
with open("fileIn.txt") as f:
    for lines in f:
        o.write(lines.replace("; ", ""))
o.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM