从csv文件创建dict

时间:2017-11-19 18:05:26

标签: python csv dictionary

我正在使用包含使用此项目生成的推文的csv文件:https://github.com/Jefferson-Henrique/GetOldTweets-python

下面是2条第一条推文和csv文件中的标题:

username;date;retweets;favorites;text;geo;mentions;hashtags;id;permalink;;
thepsalami;02-04-2014 01:59;0;2;Must be #aprilfools because everyone is 
saying #HIMYM is over! Haha it'll never stop as long as we hold fast to the 
memories.;;;#aprilfools #HIMYM; 
4,51147E+17;https://twitter.com/thepsalami/status/451146992131923968;;
shahanasiddiqui;02-04-2014 01:59;0;0;@promahuq yeah B-R was no surprise - 
the ending was just right. My FB turned into #HIMYM blog site! Man that show 
had a huge impact!;;@promahuq;#HIMYM;4,51147E+17;https://twitter.com/shahanasiddiqui/status
/451146991955759105;;

我想将其保存在dict中,以便我可以轻松访问例如用户名,时间或文本。我尝试使用csv.DictReader:

input_file = csv.DictReader(open("HIMYM_tweets.csv"))

但这导致了一些非常奇怪的事情:

{'username;date;retweets;favorites;text;geo;mentions;hashtags;id;permalink;;': 
 "thepsalami;02-04-2014 01:59;0;2;Must be #aprilfools because everyone is 
 saying #HIMYM is over! Haha it'll never stop as long as we hold fast to the 
 memories.;;;#aprilfools #HIMYM; 4", None:['51147E+17;https://twitter.com/thepsalami/status/451146992131923968;;']}
{'username;date;retweets;favorites;text;geo;mentions;hashtags;id;permalink;;': '  ....

任何关于创建这样一个词典的帮助,或者做一些更聪明的事情都是非常感激的:D

1 个答案:

答案 0 :(得分:1)

正如David的评论,你需要在使用DictReader时考虑分隔符。

只需用此替换您的代码,它就可以正常工作

input_file = csv.DictReader(open("HIMYM_tweets.csv"),delimeter=";")