简体   繁体   中英

Python 3 - reading utf-8 encoded csv into pandas

I am trying to load my utf-8 encoded csv file with data from Twitter (in polish language) into pandas dataframe in Python 3.

This is a piece of my csv:

2020-03-28 20:26:57,"b'Oj b\xc4\x99dzie impreza, oj b\xc4\x99dzie. #WyboryPrezydenckie2020 #Wybory2020 #Wybory\xc5\x9amierci'"
2020-03-28 20:26:41,"b'Skoro Prezydent ju\xc5\xbc mi\xc4\x99dzy wierszami przemyca, \xc5\xbce wybory mog\xc4\x85 by\xc4\x87 prze\xc5\x82o\xc5\xbcone, to nale\xc5\xbcy czyta\xc4\x87, \xc5\xbce wybory b\xc4\x99d\xc4\x85 prze\xc5\x82o\xc5\xbcone, a i pewnie zostanie to poprzedzone kwiecistym or\xc4\x99dziem Prezydenta w pelerynie zbawcy narodu. #koronowiruswpolsce #WyboryPrezydenckie2020'"
2020-03-28 20:24:50,"b'Idea i miara. Pomoc wyborc\xc3\xb3w i narodu g\xc5\x82osuj\xc4\x85cego dla medycyny przez #podatek_dla_demokracji, 360 mln z\xc5\x82 na subwencje dla partii i na #WyboryPrezydenckie2020 #Wybory2020 #wybory. STOP-dla-Subwencji dla partii i na wybory z mixu podatkowego.\n@tvp_info\n@Cyfrowy_Polsat\n@tvn24\n#POPiS'"

I was trying to load it this way:

df = pd.read_csv('WyboryPrezydenckie2020.csv', names=["date", "tweet"], encoding='utf-8')

but result looked like that:


    date                    tweet
0   2020-03-28 20:26:57     b'Oj b\xc4\x99dzie impreza, oj b\xc4\x99dzie. ...
1   2020-03-28 20:26:41     b'Skoro Prezydent ju\xc5\xbc mi\xc4\x99dzy wie...
2   2020-03-28 20:24:50     b'Idea i miara. Pomoc wyborc\xc3\xb3w i narodu...
3   2020-03-28 20:22:34     b'RT @wkrawcz1: Kandydat @szymon_holownia m\x...
4   2020-03-28 20:22:03     b'RT @wkrawcz1: Kandydat @szymon_holownia m\x...

and it seems that my tweets weren't decoded at all. For example the first tweet should look like that:

Oj będzie impreza, oj będzie. #WyboryPrezydenckie2020 #Wybory2020 #WyboryŚmierci

How can I solve this issue?

You've got strings for bytes (for some reason). To read it properly you need:

  1. evaluate strings to bytes
  2. decode unicode bytes to strings:

from ast import literal_eval
df = pd.read_csv('WyboryPrezydenckie2020.csv', names=["date", "tweet"], converters={"tweet":lambda x:literal_eval(x).decode("utf8")})
print(df)
                  date                                              tweet
0  2020-03-28 20:26:57  Oj będzie impreza, oj będzie. #WyboryPrezydenc...
1  2020-03-28 20:26:41  Skoro Prezydent już między wierszami przemyca,...
2  2020-03-28 20:24:50  Idea i miara. Pomoc wyborców i narodu głosując...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM