I am running this code to extract to get tweets. But running this code gives me a Syntaxerror : unexpected EOF while parsing. I am new to python so any help is appreciated! Thanks in advance.
from TwitterSearch import *
try:
tso = TwitterSearchOrder()
tso.setKeywords(['xyz', 'abc'])
tso.setLanguage('de') # we want to see German tweets only
tso.setCount(7) # please dear Mr Twitter, only give us 7 results per page
tso.setIncludeEntities(False) # and don't give us all those entity information
ts = TwitterSearch(
consumer_key = 'a',
consumer_secret = 'b',
access_token = 'c',
access_token_secret = 'd'
)
for tweet in ts.searchTweetsIterable(tso):
print('#%s tweeted: %s' % (tweet['user']['screen_name'], tweet['text']))
You need an except block at the end of your script:
except Exception, e:
print str(e)
I would suggest doing something aside from printing the exception and moving on, but this is the basic layout.
Related
I'm a beginner with coding.
I'm trying to scrape tweets from a Twitter account.
I'm getting the following error when I run my code: CRITICAL:root:twint.get:User:
Here is the code that I'm running:
import twint
config = twint.Config()
# Search tweets tweeted by user 'BarackObama'
config.Username = "BarackObama"
# Limit search results to 20
config.Limit = 20
# Return tweets that were published after Jan 1st, 2020
config.Since = "2020-01-1 20:30:15"
# Formatting the tweets
config.Format = "Tweet Id {id}, tweeted at {time}, {date}, by {username} says: {tweet}"
# Storing tweets in a csv file
config.Store_csv = True
config.Output = "Barack Obama"
twint.run.Search(config)
Does this error mean it's a problem with Twint, or is there a mistake in my code?
Thank you!
I'm a beginner as well, trying to learn python as a tool for Digital History in Brazil.
I was getting the same problem (only when using c.Username parameter).
I solved running pip3 install --upgrade -e git+https://github.com/twintproject/twint.git#origin/master#egg=twint
I hope it works for you.
The solution is in modifying user.py in the twint source, and replace lines with a try and except statement.
try:
_usr.name = ur['data']['user']['legacy']['name']
except:
_usr.name = ''
try:
_usr.username = ur['data']['user']['legacy']['screen_name']
except:
_usr.username = ''
try:
_usr.bio = ur['data']['user']['legacy']['description']
except:
_usr.bio = ''
try:
_usr.location = ur['data']['user']['legacy']['location']
except:
_usr.location = ''
try:
_usr.url = ur['data']['user']['legacy']['url']
except:
_usr.url = ''
I am facing this problem while I try to loop tweet_id using the API and write it to tweet_json.txt, the output for all data is Failed which I know is wrong
Before it was working good but when I try to Run all the code again it starts to show failed
for tweet_id in df['tweet_id']:
try:
tweet = api.get_status(tweet_id, tweet_mode = 'extended')
with open('tweet_json.txt', 'a+') as file:
json.dump(tweet._json, file)
file.write('\n')
print (tweet_id, 'success')
except:
print (tweet_id, 'Failed')
Your except is swallowing whatever exception is causing your code to die. Until you comment out the except or make it more specific you won't know if your problem is the Twitter API or file I/O or something else. Good luck!
A quick step forward would be to adjust your exception handler so that it writes the exception. I like to use the format_exc function to get my stack traces so i can write it with a logger, or however i want to handle it.
from traceback import format_exc
try:
a = "" + 1
except Exception as ex:
print("Exception encountered! \n %s " % format_exc())
Python beginner here, I'm modifying a piece of existing code (TwitterSearch on Github) to search Twitter for specific tweets that contain certain keywords using standard search API. I keep getting a Syntax Error, but it points me to blank space at the end of a line.
The thing is, the code worked once yesterday (as in I got the output I wanted) and then I tried to use it again and it keeps giving me SyntaxError.
At one point the error was at the end of the code - I deleted the last few lines and the error would simply move to whatever the end of the code was (but it always pointed at blank space rather than anything I had typed). Now it's moved to the blank space after the closing brackets following 'created at' (see below)
I've been consistently indenting the same way throughout, so I don't think it's an indentation error. For reference, I'm using Jupyter Notebook.
This is the code I'm using:
try:
tso = TwitterSearchOrder()
tso.set_keywords(['xx'])
tso.set_language('en')
tso.set_geocode('37.0902000', '-095.7129000', '1mi')
ts = TwitterSearch(
consumer_key = 'xxxx',
consumer_secret = 'xxxx',
access_token = 'xxxx',
access_token_secret = 'xxxx'
)
for tweet in ts.search_tweets_iterable(tso):
print('#%s tweeted: %s' % (tweet['user']['screen_name'], tweet['text']), (tweet['created_at']))
except TwitterSearchException as e:
print('e')
Any help would be much appreciated.
Have you tried removing : from your print:(... statement?
try:
tso = TwitterSearchOrder()
tso.set_keywords(['xx'])
tso.set_language('en')
tso.set_geocode('37.0902000', '-095.7129000', '1mi')
ts = TwitterSearch(
consumer_key = 'xxxx',
consumer_secret = 'xxxx',
access_token = 'xxxx',
access_token_secret = 'xxxx'
)
for tweet in ts.search_tweets_iterable(tso):
print('#%s tweeted: %s' % (tweet['user']['screen_name'], tweet['text']), (tweet['created_at']))
except TwitterSearchException as e:
print(e)
I am attempting to use Brickman to use Python coding on a LEGO EV3. When I try to run my code I get the following error
>>robot#ev3dev:~$ python3 CoffeePi_Test/Main.py
File "CoffeePi_Test/Main.py", line 14
tags=[‘coffeepi’]
^
SyntaxError: invalid character in identifier
Here is my code. I am not sure what is triggering this error.
#!/usr/bin/env python3
#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
import time
import vending
import ev3dev.ev3 as ev3
from ev3dev.auto import *
tags=[legovend]
words=[]
#Variables that contains the user credentials to access Twitter API
#Two versions, redudancy if the first fails...
access_token = # redacted
access_token_secret = # redacted
consumer_key = # redacted
consumer_secret = # redacted
access_token2 = # redacted
access_token_secret2 = # redacted
consumer_key2 = # redacted
consumer_secret2 = # redacted
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def on_data(self, data):
global mA,mB,home,cs, lastVend
try:
tweet = json.loads(data)
tw
except:
pass
if tags:
if all(tag in tweet['text'].lower() for tag in tags):
print (tweet['user']['screen_name'], ' - ', tweet['text'])
if int(tweet['timestamp_ms'])>lastVend:
ev3.Leds.set_color(ev3.Leds.LEFT, ev3.Leds.RED)
ev3.Leds.set_color(ev3.Leds.RIGHT, ev3.Leds.RED)
vending.onTweet(mA, mB, cs, home)
time.sleep(2)
lastVend = int(round(time.time() * 1000))+1000
ev3.Leds.set_color(ev3.Leds.LEFT, ev3.Leds.GREEN)
ev3.Leds.set_color(ev3.Leds.RIGHT, ev3.Leds.GREEN)
return True
def on_error(self, status):
print( status)
return False
if __name__ == '__main__':
#This handles Twitter authetification and the connection to Twitter Streaming API
print( 'here')
global mA,mB,home,cs, lastVend
mA = ev3.MediumMotor('outA')
mB = ev3.MediumMotor('outB')
home = mA.position - 40
cs=ColorSensor()
lastVend = int(round(time.time() * 1000))
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
auth2 = OAuthHandler(consumer_key2, consumer_secret2)
auth2.set_access_token(access_token2, access_token_secret2)
stream2 = Stream(auth2, l)
try:
Sound.speak('Ready to go').wait()
print ('trying 1')
stream.filter(track=tags)
print('trying 2')
stream2.filter(track=tags)
Sound.speak('Could not connect').wait()
except Exception as e:
print( e)
Humor is usually not welcome on stackoverflow, but there are exceptions from this rule so let's this answer be such exception.
But let's go back to answering the actual question:
Can't determine cause of SyntaxError: invalid character in identifier
I am not sure what is triggering this error.
I have to admit that I write this fully correct answer with a chuckle :) :
The cause of the SyntaxError is an invalid character in identifier.
The invalid character in the identifier is the character:
[ ’ ]
U+2019 ’ e2 80 99 RIGHT SINGLE QUOTATION MARK
Here Python code with which you can find out for yourself details about the "character" which is causing the trouble:
#!/usr/bin/ python3
# -*- coding: <utf8> -*-
# tags=[’coffeepi’]
coffeepi = "’"
print(ord(coffeepi), hex(ord(coffeepi)), bin(ord(coffeepi)))
what prints:
8217, 0x2019 , 0b10000000011001
Check out this here
http://www.utf8-chartable.de/unicode-utf8-table.pl
where I have got the information about the character from, and this here
https://docs.python.org/3/reference/lexical_analysis.html#identifiers
for more detailed information about which characters are allowed in an indentifier, because not all are and apparently this one does not belong to the range of allowed characters.
By the way: this "character" is NOT a one byte character like it is for ASCII characters. How this character is encoded in UTF-8 is specified in the Unicode table (e2 80 99).
AND ... in the entire code you have provided in the question there is no trace of what you have specified to cause the error message.
How you can fix that?
Just replace these strange quotes with standard quotes " "
ADDENDUM: The strange quotes should be probably standard quotes around a string with a word put into the list. As the Python interpreter is running into this strange quotes it assumes they are part of a variable name (identifier) and not part of a string specification. That is the reason for the confusing error message as you don't see from the code at the first glance WHY the Python interpreter thinks it deals with an variable name (identifier) and not a quoted section of text which should be turned into a Python string.
Learning python (was chosen for its ldap module) for a new script that has been tossed my way. I'm getting a sytntax error when I try using a ldif. I was getting Syntax errors on the attrs I was trying to assign until I moved it further up the script to near the search fields. I'm not exactly sure why I am getting the syntax error:
File "UserGroupModify.py", line 66
attrs = {}
^
SyntaxError: invalid syntax
~/Scripts/Termination-Script$ python2 UserGroupModify.py
File "UserGroupModify.py", line 69
ldif = modlist.addModlist(attrs)
^
SyntaxError: invalid syntax
The code currently looks like the following (including previous things I had tried all with syntax errors of their own when I tried to use them). Getting it to log in and search for the user was easy enough, but modifying the user is where I am having a hard time. The current code is uncommented and is from an example I found online.
#!/usr/bin/env python2
import ldap
import getpass
import ldap.modlist as modlist
## first you must open a connection to the server
try:
#Ignore self signed certs
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
username = raw_input("LDAP Login: ")
passwd = getpass.getpass()
userlook = raw_input("User to lookup: ")
l = ldap.initialize("ldaps://ldap.example.com:636/")
# Bind/authenticate with a user with apropriate rights to add objects
l.simple_bind_s("uid="+username+",ou=people,dc=example,dc=com", ""+passwd+"")
except ldap.LDAPError, e:
print(e)
# The dn of our existing entry/object
dn = "ou=People,dc=example,dc=com"
searchScope = ldap.SCOPE_SUBTREE
searchAttribute = ["uid"]
#retrieveAttributes = ["ou=Group"]
retrieveAttributes = ["ou"]
#searchFilter = "uid=*"
searchFilter = "(uid="+userlook+")"
#mod_attrs = [(ldap.MOD_REPLACE, 'ou', 'former-people' )]
attrs = {}
attrs['member'] = ['uid="+userlook+",ou=former-people,dc=example,dc=com']
try:
#ldap_result_id = l.search(dn, searchScope, searchFilter, retrieveAttributes)
ldap_result_id = l.search(dn, searchScope, searchFilter, retrieveAttributes)
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if (result_data == []):
break
else:
## here you don't have to append to a list
## you could do whatever you want with the individual entry
## The appending to list is just for illustration.
if result_type == ldap.RES_SEARCH_ENTRY:
print(result_data)
# Some place-holders for old and new values
#old={'Group':'l.result(ldap_result_id, 0)'}
#new={'Group':'uid="+userlook+",ou=former-people,dc=example,dc=com'}
#newsetting = {'description':'I could easily forgive his pride, if he had not mortified mine.'}
#print(old)
#print(new)
# Convert place-holders for modify-operation using modlist-module
#ldif = modlist.modifyModlist(old,new)
# Do the actual modification
#l.modify_s(dn,ldif)
#l.modify_s('uid="+userlook+,ou=People,dc=example,dc=com', mod_attrs)
#l.modify_s('uid="+userlook+",ou=People', mod_attrs)
#moved up due to SyntaxError
#attrs = {}
#attrs['member'] = ['uid="+userlook+",ou=former-people,dc=example,dc=com']
# Convert our dict to nice syntax for the add-function using modlist-module
ldif = modlist.addModlist(attrs)
# Do the actual synchronous add-operation to the ldapserver
l.add_s(dn,ldif)
# Its nice to the server to disconnect and free resources when done
l.unbind_s()
except ldap.LDAPError, e:
print(e)
Any direction pointing on what's causing the error would be greatly appreciated. Thanks
It's a syntax error to have try without except. Because there's a whole lot of unindented code before the except, Python doesn't see it as part of the try. Make sure everything between try and except is indented.
You haven't ended your try block by the time you reach this line
ldif = modlist.addModlist(attrs)
since the accompanying except is below. However, you reduced the indentation level and this is causing the syntax error since things in the same block should have the same indentation.