【问题标题】:Encoding UTF-8 when writing to CSV写入 CSV 时编码 UTF-8
【发布时间】:2014-07-01 12:55:55
【问题描述】:

我有一些简单的代码来提取一些 JSON Twitter 数据,并将一些特定字段输出到 CSV 文件的单独列中。我的问题是,我一生都无法找出将输出编码为 UTF-8 的正确方法。下面是我能得到的最接近的结果,在这里的成员的帮助下,但由于推文文本字段中的唯一字符,我仍然无法正常运行并且失败。

import json
import sys
import csv
import codecs

def main():

    writer = csv.writer(codecs.getwriter("utf-8")(sys.stdout), delimiter="\t")
    for line in sys.stdin:
        line = line.strip()

        data = []

        try:
            data.append(json.loads(line))
        except ValueError as detail:
            continue

        for tweet in data:

            ## deletes any rate limited data
            if tweet.has_key('limit'):
                pass

            else:
                writer.writerow([
                tweet['id_str'],
                tweet['user']['screen_name'],
                tweet['text']
                ])

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python csv twitter encoding utf-8


    【解决方案1】:

    来自文档: https://docs.python.org/2/howto/unicode.html

    a = "string"
    
    encodedstring  = a.encode('utf-8')
    

    如果这不起作用:

    Python DictWriter writing UTF-8 encoded CSV files

    【讨论】:

    • 感谢@user2100799 -- 我一直在尝试.encode('utf-8') 的所有变体,并且我已经阅读了文档,但我似乎仍然无法让它与 CSV 模块一起正常工作。还有其他建议吗?
    【解决方案2】:

    我也遇到了同样的问题。我有大量来自 twitter firehose 的数据,所以所有可能的并发症案例(并且已经出现)!

    我已经使用 try / except 解决了如下问题:

    如果 dict 值是一个字符串:if isinstance(value,basestring) 我尝试立即对其进行编码。如果不是字符串,我将其设为字符串,然后对其进行编码。

    如果这失败了,那是因为一些小丑在推特上发布奇怪的符号来搞乱我的脚本。如果是这种情况,首先我解码然后为字符串重新编码value.decode('utf-8').encode('utf-8')并解码,制作成字符串并为非字符串重新编码value.decode('utf-8').encode('utf-8')

    试试这个:

    import csv
    
    def export_to_csv(list_of_tweet_dicts,export_name="flat_twitter_output.csv"):
    
        utf8_flat_tweets=[]
        keys = []
    
        for tweet in list_of_tweet_dicts:
            tmp_tweet = tweet
            for key,value in tweet.iteritems():
                if key not in keys: keys.append(key)
    
                # convert fields to utf-8 if text
                try:
                    if isinstance(value,basestring): 
                        tmp_tweet[key] = value.encode('utf-8')
                    else:
                        tmp_tweet[key] = str(value).encode('utf-8')
                except:
                    if isinstance(value,basestring):
                        tmp_tweet[key] = value.decode('utf-8').encode('utf-8')
                    else:
                        tmp_tweet[key] = str(value.decode('utf-8')).encode('utf-8')
    
            utf8_flat_tweets.append(tmp_tweet)
            del tmp_tweet
    
        list_of_tweet_dicts = utf8_flat_tweets
        del utf8_flat_tweets
    
        with open(export_name, 'w') as f:
            dict_writer = csv.DictWriter(f, fieldnames=keys,quoting=csv.QUOTE_ALL)
            dict_writer.writeheader()
            dict_writer.writerows(list_of_tweet_dicts)
    
        print "exported tweets to '"+export_name+"'"
    
        return list_of_tweet_dicts
    

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-03-04
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2018-06-13
      • 2021-04-18
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      相关资源
      最近更新 更多