当我执行代码时,我遇到了错误,我不知道为什么!我从一个页面中获取此代码,通常他们的代码应该可以工作,但它不起作用
for tweet2 in find:
file = open( 'tweets.txt', 'a' )
print( "name:", tweet2.author.name )
print( "Screen-name:", tweet2.author.screen_name )
print( "Tweet created :", tweet2.created_at )
print( "tweet:", tweet2.text )
print( "Retweeted:", tweet2.retweeted )
print( "language:", tweet2.lang )
print( "Location:", tweet2.user.location )
print( "Time-zone:", tweet2.user.time_zone )
print( "Geo:", tweet2.geo )
print( "Hashtages:", tweet2.entities.get( 'hashtags' ) )
print( "------------------------------------" )
file.write(
'Name:s\nScreen-Name:s\nCreated_at:s\nTweet-Text:s\nRetweeted:s\nlanguage:s\nLocation:s\nTime_zone:'(
tweet2.author.name, tweet2.author.screen_name, tweet2.created_at, tweet2.text,
tweet2.retweeted ,tweet2.lang ,tweet2.user.location,tweet2.user.time_zone,tweet2.geo))
file.close()
-------------------------------
Tweet created : 2018-01-29 17:09:35
tweet2.lang ,tweet2.user.location,tweet2.user.time_zone,tweet2.geo))
tweet: Python for Beginners with Examples
TypeError: 'str' object is not callable
有什么建议?提前致谢
将您的file.write()
功能更改为
file.write('Name:{}\nScreen-Name:{}\nCreated_at:{}\nTweet-Text:{}\nRetweeted:{}\nlanguage:{}\nLocation:{}\nTime_zone:{}'.format(tweet2.author.name, tweet2.author.screen_name, tweet2.created_at, tweet2.text, tweet2.retweeted ,tweet2.lang ,tweet2.user.location,tweet2.user.time_zone))
这是你的问题。
file.write(
'Name:s\nScreen-Name:s\nCreated_at:s\nTweet-Text:s\nRetweeted:s\nlanguage:s\nLocation:s\nTime_zone:'(
tweet2.author.name, tweet2.author.screen_name, tweet2.created_at, tweet2.text,
tweet2.retweeted ,tweet2.lang ,tweet2.user.location,tweet2.user.time_zone,tweet2.geo))
这部分是一个字符串:
'Name:s\nScreen-Name:s\nCreated_at:s\nTweet-Text:s\nRetweeted:s\nlanguage:s\nLocation:s\nTime_zone:'(
紧随其后,你有一个左括号。这是一个函数调用。您试图像函数一样调用该字符串。 Python正确地在这个BS上打电话给你。
我假设你想把其他值作为字符串的一部分写入文件,可能是你有s
的地方。这应该是%s
,你应该在字符串和值之间使用%
运算符。作为评论中的sng注释,您似乎也缺少占位符,也可能没有正确数量的值。作为第一次尝试,将该行更改为:
'Name:%s\nScreen-Name:%s\nCreated_at:%s\nTweet-Text:%s\nRetweeted:%s\nlanguage:%s\nLocation:%s\nTime_zone:%s' % (
您也可以使用.format()
作为A Magoon建议;这是更新的方式。我建议%
,因为它看起来像你想要做的。