2017-07-08 71 views
0

我是python的新手,我正在寻找一些帮助来创建一个存储来自两个不同变量的数据的循环。此方法仅保存第一条推文。将数据保存到不同变量的csv

# Twitter Loop 

for tweet in tweepy.Cursor(api.search,q=search+ 
     " -filter:retweets", 
     result_type='recent', 
     lang="en").items(num_tweets): 

    raw = tweet.text 

    # Text processing 

    clean = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", raw) 

    result = cool.api(clean) 

# CSV File 

import csv 
f = open("file.csv", "a") 
c = csv.writer(f) 
c.writerow([clean, result]) 
f.close() 

我做了很多的尝试,我不知道什么是应该做it.n我是否应为每一个变量循环的正确方法是什么?

回答

1

简单。您需要将您的呼叫转移到您的for循环内的csv.writerow()。这样一来,每次迭代鸣叫将被写入到CSV文件(或者更精确地说,从鸣叫grepped数据):

import csv 

f = open("file.csv", "a", newline="") 
c = csv.writer(f) 

for tweet in tweepy.Cursor(api.search,q=search+ 
     " -filter:retweets", 
     result_type='recent', 
     lang="en").items(num_tweets): 

    raw = tweet.text 
    clean = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", raw) 
    result = cool.api(clean) 
    c.writerow([clean, result]) # Write each tweet to the csv file. 
f.close() 

你的代码可以使用上下文经理声明with提高。这意味着无论发生什么情况,您的文件将始终关闭:

import csv 


with open('file.csv', 'a') as file: 
    c = csv.writer(file) 
    for tweet in tweepy.Cursor(api.search,q=search+ 
     " -filter:retweets", 
     result_type='recent', 
     lang="en").items(num_tweets): 

     raw = tweet.text 
     clean = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", raw) 
     result = cool.api(clean) 
     c.writerow([clean, result]) 
+0

非常感谢!你知道为什么我的结果之间有空行吗? –

+0

你的意思是你正在写入csv文件的行之间有额外的行,@YoussefS。 –

+0

是http://imgur.com/a/hmX8S –