推文中的逗号破坏了我的数据文件

问题描述 投票:-1回答:1

我一直在使用这段代码,我遇到的问题是当我从Twitter API中取出时,逗号分隔我的CSV文件中的单元格。一些推文和Twitter给你的一些数据包含逗号,所以我的单元格最终会出现在不同的列上。例如,虽然一条推文的文本可能在第三列中,但另一条推文可能在第三列,第四列和第五列中。我需要一些方法来解决这个问题。

这是我的代码:

class listener(StreamListener):

    def on_data(self, data):
        # Check for a field unique to tweets (if missing, return immediately)
        if "in_reply_to_status_id" not in data:
            return
        with open("trump.csv", 'a') as saveFile:
            try:
                saveFile.write(json.dumps(data.replace(",",",")) + "\n")


            except (BaseException, e):
                print ("failed on data", str(e))
                time.sleep(5)
            return True
    def on_error(self, status):
        print (status)
python api twitter streaming
1个回答
0
投票

首先,csv可以以引用块中的逗号被视为块的一部分的方式生成,请参阅this post。它有两个答案,一个使用双引号,另一个反转,我不确定实际的是什么。

import csv

with open('trump.csv', 'rb') as inputfile:
    rows = csv.reader(inputfile, delimiter=',', quotechar='`')
    for row in rowreader:
        print row

如果这不适用并且您需要完全删除文件中的逗号,请执行以下操作:

with open("trump.csv") as inputfile, open("output.csv", "w") as outputfile:
    for line in inputfile:
        outputfile.write(line.replace(",", ""))

或者您可以输入任何内容,您可以操纵字符串并替换空格的逗号。

© www.soinside.com 2019 - 2024. All rights reserved.