类型错误:file()最多接受3个参数(给出了4个)

9
我是一名能够帮助翻译的助手。
我在Mac上使用Spyder,Spyder中的Python版本为2.7。几个月前,我使用以下代码来抓取推文,但现在发现它已经不起作用了。首先,我不能再使用:
from urllib.request import url open

现在使用:

from urllib2 import url open

然而,我无法运行下面的代码并出现以下错误:“with open('%s_tweets.csv' % screen_name,'w',newline =' ',encoding ='utf-8-sig')as f:TypeError:file()最多接受3个参数(给出4个)”

import sys
from urllib2 import urlopen

default_encoding = 'utf-8'

import tweepy #https://github.com/tweepy/tweepy
import csv

#Twitter API credentials
consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""

screenNamesList = []

def redirect(url):
page = urlopen(url)
return page.geturl()

def get_all_tweets(screen_name):
#Twitter only allows access to a users most recent 3240 tweets with this method

#authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth, wait_on_rate_limit = True)

#initialize a list to hold all the tweepy Tweets
alltweets = []  

#make initial request for most recent tweets (200 is the maximum allowed count)
new_tweets = api.user_timeline(screen_name = screen_name,count=200)

#save most recent tweets
alltweets.extend(new_tweets)

#save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1

#keep grabbing tweets until there are no tweets left to grab
while len(new_tweets) > 0:
    #print "getting tweets before %s" % (oldest)

    #all subsiquent requests use the max_id param to prevent duplicates
    new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)

    #save most recent tweets
    alltweets.extend(new_tweets)

    #update the id of the oldest tweet less one
    oldest = alltweets[-1].id - 1

    #print "...%s tweets downloaded so far" % (len(alltweets))

#transform the tweepy tweets into a 2D array that will populate the csv 
outtweets = [[tweet.id_str, tweet.created_at, tweet.text, tweet.retweet_count, tweet.coordinates, tweet.favorite_count, tweet.author.followers_count, tweet.author.description, tweet.author.location, tweet.author.name] for tweet in alltweets]

#write the csv  

with open('%s_tweets.csv' % screen_name, 'w', newline='', encoding='utf-8-sig') as f:
    writer = csv.writer(f)
    writer.writerow(["id", "created_at", "text", "retweet_count", "coordinates", "favorite_count", "followers_count", "description", "location", "name"])
    writer.writerows(outtweets)

pass


if __name__ == '__main__':   
#pass in the username of the account you want to download
for i, user in enumerate(screenNamesList):
    get_all_tweets(screenNamesList[i])
    i+=1
1个回答

10

这段代码适用于Python 3,其中open函数有新参数:

  • encoding
  • newline

在Python 2中,只有三个可能的参数:

open(name[, mode[, buffering]])

buffering并不是你想要的。其他参数也都不可用。

你可以通过使用以下方法进行解决:

with open('%s_tweets.csv' % screen_name, 'wb') as f:

以二进制方式打开句柄可以修复 csv 模块的“空行”错误。对于Python 3(仅限“旧”版本,最新版本不需要),您必须传递 newline="",因为无法以二进制方式打开 csv 文件。

要处理编码和换行符,只需按照此处所述进行即可。

from io import open

并且不改变你的代码的其余部分。好吧,几乎是这样,你需要像这样为标题添加 Unicode 前缀:

writer.writerow([u"id", u"created_at", u"text", u"retweet_count", u"coordinates", u"favorite_count", u"followers_count", u"description", u"location", u"name"])

太好了,谢谢 - 它起作用了。但是,我该在哪里添加“encoding ='utf-8-sig'”呢?或者,我应该尝试在Python 3中运行Spyder吗? - bayrah
检查我的编辑。我认为你可以使用Python 2.7的io模块来处理这个问题。 - Jean-François Fabre
谢谢。它报错了:"write() argument 1 must be unicode, not str after "writer.writerow(["id", "created_at", "text", "retweet_count", "coordinates", "favorite_count", "followers_count", "description", "location", "name"])。 - bayrah
你需要将标题编码为Unicode,检查我的编辑。这种编码对你真的有用吗? - Jean-François Fabre
我感谢您的评论。不幸的是,我仍然遇到相同的错误。我已经升级了我的Anaconda/Spyder,以便我可以使用Python 3。 - bayrah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接