I'm trying to program a reddit bot, but get this error message:
Traceback (most recent call last):
File "main.py", line 64, in <module>
run_bot(r, comments_replied_to)
File "main.py", line 34, in run_bot
comments_replied_to.append(comment.id)
AttributeError: 'filter' object has no attribute 'append'
Here is my code: https://pastebin.com/caz14jm7
I think I have to change append into a list, but I don't know how to do that
Part of this is a version difference. In Python 2, filter returned a list. In Python 3, filter returns a generator, which you are treating like a list. The filter generator does not have an append method.
So, you just need to turn it into a list:
comments_replied_to = list(filter(None, comments_replied_to))
Or, even better (in the opinion of many):
comments_replied_to = [k for k in comments_replied_to if k]
I have 2 potential solutions for you,
solution 1:
Line 55 You can change like this
comments_replied_to = List(filter(None, comments_replied_to))
so that, your get_saved_comments() will return a list.
This will help you use the append method and comments_replied_to.append(comment.id) should work without any error
Solution 2:
Line 60: You can change like this
comments_replied_to = list(get_saved_comments())
As long as comments_replied_to is a list type, it will allow you to append method without any issues.
check this blog to have a better understanding over append method
https://www.programiz.com/python-programming/methods/list/append
Related
Having an error where i'm trying to get the first work from a string that is passed in to a method within a class. But i am getting AttributeError: 'Deck' object has no attribute 'split' when I run. The 'new_card' that is passed in will be for example 'Two of Hearts'. and new_Card is a string and self.values is a dictionary
# returns integer value of a card
def get_card_value(self, new_card):
return self.values[new_card.split()[0]]
and the error:
Traceback (most recent call last):
File "/home/andypaling/Documents/Programming/python/random/card_game/game.py", line 146, in
if not Game.check_same_cards(player1_deck, player2_card):
File "/home/andypaling/Documents/Programming/python/random/card_game/game.py", line 87, in check_same_cards
if card1.get_card_value(card1) == card2.get_card_value(card2):
File "/home/andypaling/Documents/Programming/python/random/card_game/game.py", line 40, in get_card_value
split_string = new_card.split(' ')
thanks for any help
Hey it seems like you are using a diffrent data type and not a string in your case judging that your making a card game i am guessing you are using a tuple. Try converting the data to a string then split it using the .split() function.
I hope this can help.
I have captured a string from a REST get request and have placed it in a variable. The string is:
{"name":"na1mailboxarchive","objectCount":49564710,"dataBytes":36253526882451},{"name":"na1mailboxarchive2","objectCount":17616567,"dataBytes":13409204616615}
I am trying to convert it to a dictionary so I can increment through it and capture the bucket name, size and object count. I have tried eval()
bucket_dict = eval(bucket_info)
but the program errors out with a:
Traceback (most recent call last):
File "./test.py", line 83, in <module>
for k,b in bucket_dict.items():
AttributeError: 'tuple' object has no attribute 'items'
When I print the value of bucket_dict I get:
({'name': 'na1mailboxarchive', 'objectCount': 49564710, 'dataBytes': 36253526882451}, {'name': 'na1mailboxarchive2', 'objectCount': 17616567, 'dataBytes': 13409204616615})
I think the foul up is the () at the beginning and the end of the dictionary. Nothing else I have tried works either.
Try this instead
import ast
string = '{"name":"na1mailboxarchive","objectCount":49564710,"dataBytes":36253526882451},{"name":"na1mailboxarchive2","objectCount":17616567,"dataBytes":13409204616615}'
result = ast.literal_eval(string)
print(result)
result is returned as a dictionary
I got it figured out.
Firstly the json return from the REST API get is badly formatted. I will take that up with the vendor. Secondly I used some iof the infrmation form #PrashantKumar and #MisterMiyagi to sus out the issue I was having. In my original code I had loaded the list with:
bucket_info = [acct_string[acct_string_start+11:acct_len-4]]
The variable was capturing the leading "[" and trailing "]" as a part of the string. Once I removed them then the list behaved correctly and I now can work with it. Thank you for the information and the trail markers.
I want to use .find() like this for mongoDB in Python :
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27000')
db = client['responsi']
cursor = db['produk']
for x in cursor.find({"pricing.pct_savings":{"$gt":25}}).sort({"pricing.pct_savings":-1}):
print(x)
But, it showing error like this :
Traceback (most recent call last):
File "Find.py", line 7, in <module>
for x in cursor.find({"pricing.pct_savings":{"$gt":25}}).sort({"pricing.pct_savings":-1}):
File "G:\PROGRAM FILES\Python\lib\site-packages\pymongo\cursor.py", line 708, in sort
keys = helpers._index_list(key_or_list, direction)
File "G:\PROGRAM FILES\Python\lib\site-packages\pymongo\helpers.py", line 69, in _index_list
raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list
How to solved this problem?
Thank you!
Sorry, I have bad score in english.
As opposed to the mongo shell, pymongo takes key and direction as the arguments to the sort method (or list, but that's another form that is not relevant to you currently, I'll show it too)
So your query should actually be cursor.find({"pricing.pct_savings":{"$gt":25}}).sort("pricing.pct_savings", pymongo.DESCENDING)
The other form gets a list of tuples of field name and the direction, and allows you to sort by multiple fields, for example collection.find().sort([('my_field_1',pymongo.DESCENDING), ('my_field_2',pymongo.ASCENDING)])
See the relevant documentation here https://api.mongodb.com/python/current/api/pymongo/cursor.html?highlight=sort#pymongo.cursor.Cursor.sort
You can find the ASCENDING and DESCENDING constants here https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.ASCENDING
BTW (not related to your original question)
db['produk'] is actually a collection, not a cursor, so it would be better if you would call it collection, and not cursor.
Cursor is what find() returns
should only have this structure
from bson import ObjectId
id = '375g68h97b680jf78j'
data = cursor.find_one_and_delete({'_id': ObjectId(id)})
I am following instructions for a class homework assignment and I am supposed to look up the top 200 most frequently used words in a text file.
Here's the last part of the code:
fdist1 = FreqDist(NSmyText)
vocab=fdist1.keys()
vocab[:200]
But when I press enter after the vocab 200 line, it returns:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict_keys' object is not subscriptable
Any suggestions on how to fix this so it can correctly return an answer?
Looks like you are using Python 3. In Python 3 dict.keys() returns an iterable but not indexable object. The most simple (but not so efficient) solution would be:
vocab = list(fdist1.keys())[:200]
In some situations it is desirable to continue working with an iterator object instead of a list. This can be done with itertools.islice():
import itertools
vocab_iterator = itertools.islice(fdist1.keys(), 200)
I am using python 3.5 and I meet the same problem of TypeError.
Using vocab = list(fdist1.keys()) does not give me the top 50 most frequently used words.
But fdist1.most_common(50) does.
Further,if you just want to show those top 50 words not with their frequency,you can try :
[word for (word, freq) in fdist1.most_common(50)]
If you want to get elements as keys and values (word and frequency), you can use:
list(fdist1.items())[:200]
To print the most frequently used 200 words use:
fdist1.most_common(200)
The above line of code will return the 200 most frequently used words as key-frequency pair.
If your using python 3 try:
fdist1.most_common(200)
instead, to get the 200 most frequent words.
fdist1 = FreqDist(NSmyText)
vocab=fdist1.keys()
This code is using in Python2.7.
So you should do some change.
dic.keys() returns an iteratable. So using:
list(fdist1.keys())
I have a section of code that somehow fails on the following list.index function:
for line in flines:
for match in bad_data_regex.findall(line):
assert line in flines
index = flines.index(line)
flines.pop(index)
# other code that does not modify flines ....
My code fails on:
ScriptEngine.execute:Error in script Traceback (innermost last):
File "<string>", line 168, in ?
ValueError: list.index(x): x not in list
If the value truly wasn't in the list, I should've gotten an AssertionError before the list.index function.
I'm using Jython 2.2.1 under Java version 1.6.0_18.
How is this possible?
EDIT:
Turns out the code that was generating that error was not what I have posted above. My Jython interpreter gave me the wrong line number, and happened to land on the line with the index function above.
The above code does work as I intended, although I realize it's not the best practice to modify a list while iterating over it. I'll try to avoid that whenever possible in the future.
This probably happens because of the flines.pop(index) part. It is always a bad idea to change the list while you iterate over it.
Consider this example:
In [1]: a = range(5)
In [2]: for i in a:
...: print a.pop()
...:
4
3
2
In [3]: a
Out[3]: [0, 1]