from newsapi.sources import Sources
import json
api_key ='*******************'
s = Sources(API_KEY=api_key)
they input the category of news they want
wanted = input('> ')
source_list = s.get(category=wanted, language='en')
index = 0
sources = []
getting the sources
for source in source_list["sources"]:
data = json.dumps(source_list)
data = json.loads(data)
source = (data["sources"][index]["url"])
sources.append(source)
index += 1
from newspaper import Article
i = len(sources) - 1
looping through the source list and printing the articles
for source in sources:
url_ = sources[i]
a = Article[url_]
print(a)
i -= 1
getting error 'type' object is not subscriptable on the line a = Article[url_] have researched but still do not understand why in my case.
The simple solution to your problem is that the line:
a = Article[url_]
Should be:
a = Article(url_)
Now to get to why you're getting the TypeError: 'type' object is not subscriptable error.
This TypeError is the one thrown by python when you use the square bracket notation object[key] where an object doesn't define the __getitem__ method. So for instance, using [] on an object throws:
>>> object()["foo"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'object' object is not subscriptable
In this case []s were used accidentally instead of ()s when trying to instantiate a class. Most classes (including this Article class) are instances of the type class, so trying object["foo"] causes the same error you are experiencing:
>>> object["foo"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Related
Here is a function to check the data and update it
div , update are my mongodb collection object
def data_updater(user1_id,code):
device_id = dvi.find_one({"user_id":user1_id},{"_id":0,"user_id":0})["device_id"]
prv_data = update.find_one({"device_id":device_id},{"_id":0,"device_id":0})
prv_date = prv_data["date"]
msg = prv_data["message"]
if prv_date < current_date and msg != code:
x = update.find_one_and_update({"device_id":id,},{"$set":message":code,"date":current_date}})
print(x.acknowledged)
and when I am calling the function it is giving TypeError data_updater(95626,972681)
the error
Traceback (most recent call last):
File line 170, in <module>
data_updater(95626,972681)
File line 71, in data_updater
device_id = dvi.find_one({"user_id":int(user1_id)},{"_id":0,"user_id":0})["device_id"]
TypeError: 'NoneType' object is not subscriptable
I am not able to find any mistake please help
Your context isn't very clear, however, from the error trace as generated it seems that your find_one() function returns None with the arguments as passed and you are trying to access the value for the key device_id. I recommend you refactor your find_one() function or make use of the following code to resolve the issue at hand:
def data_updater(user1_id,code):
try:
device_id = dvi.find_one({"user_id":user1_id},{"_id":0,"user_id":0})["device_id"]
prv_data = update.find_one({"device_id":device_id},{"_id":0,"device_id":0})
prv_date = prv_data["date"]
msg = prv_data["message"]
if prv_date < current_date and msg != code:
x = update.find_one_and_update({"device_id":id,},{"message":code,"date":current_date}})
print(x.acknowledged)
except TypeError:
print('No value found for specified parameters :/')
PS: I also didn't understand the use of $ in your code, so I removed it thinking of it as a mistake. Hope this helps! 😊
I have a problem with my code
pageNameOrId = 'Ch3Thailand'
source_url = 'https://www.facebook.com/pg/%s/posts/' % pageNameOrId
content = html.unescape(requests.get(source_url).text)
postInfos = getPostInfosFromContent(content)
posts = getPostsFromContent(content, postInfos)
urlResult = re.search(r'\/pages_reaction_units.*?unit_count=8', content).group()
print(len(posts), posts[-1])
and get errors like this
AttributeError Traceback (most recent call last)
<ipython-input-29-69969f51fdc6> in <module>()
----> 6 urlResult = re.search(r'\/pages_reaction_units.*?unit_count=8', content).group()
AttributeError: 'NoneType' object has no attribute 'group'
This code
re.search(r'\/pages_reaction_units.*?unit_count=8', content)
Simply equals to None. Perhaps the regex didn't match anything, so it returned None.
I was running python code below:
def dict2struct(d):
res = namedtuple("config", d.keys())(*d.values())
return res
cfg = {'fieldx': 'Allan', "fieldy": 45, 'fieldt': {'head': False, 'number': 2}}
res = dict2struct(cfg)
print(res)
res.fieldx = "Jack"
and got the error:
config(fieldx='Allan', fieldy=45, fieldt={'head': False, 'number': 2})
Traceback (most recent call last):
File "*****\Testings\test_x.py", line 97, in <module>
res.fieldx = "Jack"
AttributeError: can't set attribute
I have read the questions below and understand that it was because namedtuples are immutable and the property setter was restricted.
AttributeError: can't set attribute
AttributeError: can't set attribute in python
However, I need to convert a lot of strings from a configurational dictionary's keys to properties of a struct or a class. These strings values are not fixed as they are many.
Is there a way to get around of this AttributeError for my problem?
Steve's solution above worked for me.
pypi.org/project/attributedict
When I enter the following:
str = str.replace("something", "something_else")
It returns with:
AttributeError: 'tuple' object has no attribute 'replace'
I am on Python 3.6.5. Any help would be appreciated.
Check the content of str. It contains a tuple, not a string. Is it the output from a .split() operation or suchlike?
For example:
>>> str = ( 'a', 'b', 'banana' )
>>> str.replace("something", "something_else")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'replace'
Obviously it does work with the correct str:
>>> str = 'banana'
>>> str.replace("something", "something_else")
>>>
With this script i'm trying to iterate through my timeline with the twitter api.
I'm using time delay in a "for" loop to get all of my tweets in a List of objects like this:
x = [<twitter.status.Status at 0x7fb23b7c5090>, <twitter.status.Status at 0x7fb5fdb7c5090>,<twitter.status.Status at 0x7fbs4b7c5090>,<twitter.status.Status at 0x7f255b7c5090>, ...]
#Setting the connection:
api = twitter.Api(consumer_key= cons_key,
consumer_secret = cons_secret,
access_token_key = accs_token,
access_token_secret = accs_token_secret)
#Getting the latest id and put it on a list called "lis"
x = api.GetUserTimeline(screen_name = "My_Username", count = 1, include_rts = True)
lis=[x[0].id]
#Creating a list to append my twitter status objects.
tweet_info = []
## Iterate through all tweets, say for example 4 times
for i in range(0, 4):
## tweet extract method with the last list item as the max_id
user_timeline = api.GetUserTimeline(screen_name="My_Username",
count=3, include_rts = True, max_id=lis[-1])
time.sleep(2) ## 2 seconds rest between api calls
for tweet in range(len(user_timeline)):
x = user_timeline[tweet]
tweet_info.append(x)
lis.append(tweet['id']) #appending the id's in order to my list in order to extract the last one for the next time it iterates.
When i run my code i'm getting this error:
TypeError Traceback (most recent call last)
<ipython-input-103-11f235fc3b3a> in <module>()
7 x = user_timeline[tweet]
8 tweet_info.append(x)
----> 9 lis.append(tweet['id'])
TypeError: 'int' object has no attribute '__getitem__'
What am I doing wrong and how can be fixed?
It is because tweet is an integer
Your code:
for tweet in range(len(user_timeline)):
x = user_timeline[tweet]
tweet_info.append(x)
lis.append(tweet['id'])
You are internally doing this:
1["id"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'
That is :
for i in range(len(a)):
print i
print i["id"]
1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'