This code works for the first line of the input file but fails in the second trial and I don't know why. I tried to see if there are similar questions but I didn't found a solution.
carac=":"
fichier = open("test", "r")
for i in range(2):
time.sleep(0.5)
chaine = fichier.readline().split(carac)
print(chaine[0])
driver = webdriver.Chrome(r'C:\Users\bh\Downloads\chromedriver')
driver.get('https://www.twitter.com/login')
username_box = driver.find_element_by_class_name('js-username-field')
username_box.send_keys(chaine[0])
password_box = driver.find_element_by_class_name('js-password-field')
password_box.send_keys(chaine[1])
I have this error:
Traceback (most recent call last):
File "C:/Users/bh/PycharmProjects/test/twitter.py", line 199, in <module>
password_box.send_keys(chaine[1])
IndexError: list index out of range
ps: the document is a .txt
in the document there is something like this :
test#gmail.com:pass
test#gmail.com:pass
this happens because you havent assigned a value to chaine[1].
You need to declare it before you use it. Why you use a sleep function?
print chaine[1] to see if its empty or not
Related
I want to access large range value as this higher end value will be change sometimes as I couldnt able to print last value, If I give lower range it is getting printed but when I give higher range like 73138176 or more than 7 digits it is getting memory error,as I am using Python 2.7.10, can anyone help me to get print the value of last range in this version of Python
lbas_on_bank = []
start=0
end=73138176
for lba in range(start,end):
if len(lbas_on_bank)>50:
lbas_on_bank = []
else:
lbas_on_bank.append(lba)
last_written_lba = lbas_on_bank[-1]
print(last_written_lba)
output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError
Use xrange() instead of range()
Or
try:
your code..
except MemoryError as er:
print(er)
I've seen a few similar answers concerning KeyErrors from using groupby in DataFrame. However, their solutions and explanations don't fit my issue properly.
I find this particularly strange because I can't replicate the exception when I'm testing the script in the Python console, by feeding it with code line by line. The groupby attempt works normally when tested with one-entry examples.
Additionally, I had earlier used the same script for a similarly-formatted json, though with significantly smaller data size - and it worked seamlessly.
What am I trying to do?
I have a nested json string that I'm attempting to format using DataFrame, count the number of times a specific value appears in each column.
The json when put through a converter looks like this:
action,timestamp,campaign_id,title,type,url
open,2019-02-08T08:57:59+00:00,192a39071b,[CAMPAIGN TITLE],,
sent,2019-02-08T07:00:00+00:00,192a39071b,[CAMPAIGN TITLE],regular,
sent,2019-02-07T11:00:00+00:00,2159592071,[CAMPAIGN TITLE],regular,
open,2019-02-07T08:33:44+00:00,214d84380b,[CAMPAIGN TITLE],,
open,2019-02-07T08:33:19+00:00,56ab3a5934,[CAMPAIGN TITLE],,
open,2019-02-07T08:32:33+00:00,811ac6cae3,[CAMPAIGN TITLE],,
sent,2019-02-07T02:45:00+00:00,214d84380b,[CAMPAIGN TITLE],regular,
sent,2019-02-05T02:30:00+00:00,56ab3a5934,[CAMPAIGN TITLE],regular,
(in case it's relevant - the json is pulled directly from an API and not written in a csv or anything)
Specifically, I want to count the number of times "open", and "sent" appear under the column for "action".
This is the relevant snippet of the code I used:
dretrieved = json.loads(response.text)
dframed = pandas.DataFrame(dretrieved['activity'])
actionssummary = dframed.groupby('action').size()
try: opencount = actionssummary['open']
except:
opencount = 0
try: sentcount = actionssummary['sent']
except:
sentcount = 0
And this was the traceback:
Traceback (most recent call last):
File "MC_member_data_list_api.py", line 92, in <module>
actionssummary = dframed.groupby('action').size()
File "C:\Users\username\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\generic.py", line 7622, in groupby
observed=observed, **kwargs)
File "C:\Users\username\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\groupby\groupby.py", line 2110, in groupby
return klass(obj, by, **kwds)
File "C:\Users\username\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\groupby\groupby.py", line 360, in __init__
mutated=self.mutated)
File "C:\Users\username\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\groupby\grouper.py", line 578, in _get_grouper
raise KeyError(gpr)
KeyError: 'action'
Anyone has a clue what's going on?
EDIT: Following suvayu's comment about Heisenbugs caused by unexpected or malformed input, I added an Exception-pass to my code as below, so that it would record a zero (0) for that user's entry and move on to the next:
dframed = pandas.DataFrame(dretrieved['activity'])
# identify action portion of the json (go to next if error)
try: actionssummary = dframed.groupby('action').size()
except:
pass
# identify count of opens
try: opencount = actionssummary['open']
except:
opencount = 0
I am processing a tab-delimited data set of almost three million lines. Since I have enough memory, I am loading the entire data file into memory via a list. I then go and clean up inconsistencies with the data row-by-row. After 150,000 lines of successful computation, the program halts with this error:
Traceback (most recent call last):
File "C:/Users/me/dataset_cleanup_utility/dataset_cleanup.py", line 466, in <module>
ROWS_PASSED = passed
File "C:/Users/me/dataset_cleanup_utility/dataset_cleanup.py", line 43, in dataset_cleanup
row = make_consistent(row, row_count)
File "C:/Users/me/dataset_cleanup_utility/dataset_cleanup.py", line 180, in make_consistent
row[11] = remove("(STAFF)", "", str(row[11]))
IndexError: string index out of range
The code sample that causes this is below:
if "(STAFF)" in str(row[11]):
row[11] = remove("(STAFF)", "", str(row[11]))
def remove(unwanted, wanted, _str):
s = str(_str).rsplit(unwanted, 1)
if len(s) == 2:
return str(s[0]) + wanted + str(s[1])
else:
return str(s[0]) + wanted
Here, row is the list containing all of the columns for a given row and the IndexError is being thrown INSIDE the if statement that checks row[11]. So what this error is telling me is that the row[11] was okay when evaluating the if statement, but inside the if statement, when evaluated again, row[11] no longer exists. How could this be if no changes to row[11] occurred after the if statement was evaluated?
Error:
Traceback (most recent call last):
File "<string>", line 10, in <module>
File "/Users/georg/Programmierung/Glyphs/Glyphs/Glyphs/Scripts/GlyphsApp.py", line 59, in __iter__
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/objc/_convenience.py", line 589, in enumeratorGenerator
yield container_unwrap(anEnumerator.nextObject(), StopIteration)
objc.error: NSGenericException - *** Collection <__NSArrayM: 0x7f9906245480> was mutated while being enumerated.
I know this error occurs because I'm trying to delete objects from the array while also enumerating these objects. But I don't know how to solve it. I'm fairly new to object orientated programming and am limiting myself to scripting.
I searched the web and it seems to solve the error, I have to copy the array before deleting objects from it. When I'm tying to copy the array via deepcopy
import copy
pathcopy = copy.deepcopy(thisLayer.paths)
right before for path in thisLayer.paths:
But in this case I get the following error:
Cannot pickle Objective-C objects
Usually the program crashes after the first Glyph. For clarification: I work in Glyphsapp, a Typedesigning software.
Here is the Code:
# loops through every Glyph and deletes every path with nodes on the left half
for myGlyph in Glyphs.font.glyphs:
glname = myGlyph.name
thisLayer = Glyphs.font.glyphs[glname].layers[1]
middle = thisLayer.bounds.size.width/2+thisLayer.LSB
thisGlyph = thisLayer.parent
for path in thisLayer.paths: # this is where the code crashes
for thisNode in path.nodes:
if thisNode.position.x < middle:
#print thisNode.position.x
try:
thisLayer = path.parent()
except Exception as e:
thisLayer = path.parent
try:
thisLayer.removePath_ ( thisNode.parent() )
except AttributeError:
pass
Thank you in advance
Thank you very much Andreas,
with your help I was able to fix my code :-)
Here is the outcome:
for myGlyph in Glyphs.font.glyphs:
glname = myGlyph.name
thisLayer = Glyphs.font.glyphs[glname].layers[1]
middle = thisLayer.bounds.size.width/2+thisLayer.LSB
thisGlyph = thisLayer.parent
for path in thisLayer.paths:
for thisNode in path.nodes:
if thisNode.position.x < middle:
nodeList = []
nodeList.append(thisNode.parent())
nLCopy = nodeList[:]
for ncontainer in nLCopy:
thisLayer.removePath_ ( ncontainer )
I'm trying to simulate a substring in Python but I'm getting an error:
length_message = len(update)
if length_message > 140:
length_url = len(short['url'])
count_message = 140 - length_url
update = update["msg"][0:count_message] # Substring update variable
print update
return 0
The error is the following:
Traceback (most recent call last):
File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 54, in <module>
x.updateTwitterStatus({"url": "http://xxx.com/?cat=49s", "msg": "Searching for some ....... tips?fffffffffffffffffffffffffffffdddddddddddddddddddddddddddddssssssssssssssssssssssssssssssssssssssssssssssssssseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddfffffffffffffffffffffffffffffffffffffffffffff "})
File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 35, in updateTwitterStatus
update = update["msg"][0:count_message]
TypeError: string indices must be integers
I can't do this?
update = update["msg"][0:count_message]
The variable "count_message" return "120"
Give me a clue.
Best Regards,
UPDATE
I make this call, update["msg"] comes from here
x = TwitterC()
x.updateTwitterStatus({"url": "http://xxxx.com/?cat=49", "msg": "Searching for some ...... ....?fffffffffffffffffffffffffffffdddddddddddddddddddddddddddddssssssssssssssssssssssssssssssssssssssssssssssssssseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddfffffffffffffffffffffffffffffffffffffffffffffddddddddddddddddd"})
Are you looping through this code more than once?
If so, perhaps the first time through update is a dict, and update["msg"] returns a string. Fine.
But you set update equal to the result:
update = update["msg"][0:int(count_message)]
which is (presumably) a string.
If you are looping, the next time through the loop you will have an error because now update is a string, not a dict (and therefore update["msg"] no longer makes sense).
You can debug this by putting in a print statement before the error:
print(type(update))
or, if it is not too large,
print(repr(update))