AttributeError: 'tuple' object has no attribute 'items' - list

import re, time, _thread
import urllib.request
from bs4 import BeautifulSoup
def get_data(n):
global s,r
html=urllib.request.urlopen('http://www.fmkorea.com/index.php?mid=best&listStyle=webzine&page='+str(n))
soup=BeautifulSoup(html,'lxml')
l=soup.findAll('h3', {'class':'title'})
for i in l:
for j in re.split(r'''\)|\(|\'|\"|\?|\]|\[|,|\.|\ |\:''',i.text[:i.text.rfind('[')].strip()):
s[j.strip()] = s.get(j.strip(),0) + 1
r=r+1
s={}
r=0
for _ in range(1,2037):
_thread.start_new_thread(get_data, (_,))
time.sleep(0.05)
while r!=2036:
time.sleep(3)
with open('res','w') as f:
s=sorted(s.items(),key=lambda x: x[1],reverse=True)
for i in s:
f.writelines(str(i[0]) + " : " + str(i[1])+"\n")
AttributeError Traceback (most recent call last)
<ipython-input-24-3e6cc449e797> in <module>()
35 #
36 with open('res','w') as f:
---> 37 s=sorted(s.items(),key=lambda x: x[1],reverse=True)
38 for i in s:
39 f.writelines(str(i[0]) + " : " + str(i[1])+"\n")
AttributeError: 'list' object has no attribute 'items'
I keep getting this error for the code above and cannot seem to fix it. How do I prevent the AttributeError from being raised?

items is for dictionaries you cant use it on list
>>> d = {1:'a'}
>>> d.items()
dict_items([(1, 'a')])
>>> l = [1,2]
>>> l.items()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'items'

Related

Appending list but got "AttributeError: 'NoneType' object has no attribute 'append'" Python 2.7

I keep having this error on my code, which says:
"AttributeError: 'NoneType' object has no attribute 'append'"
But there is interesting fact, it only occurs when "n" is odd.
Here is the piece of code I'm using:
Note: I'm using Python 2.7.18
def sol(n, df):
if n == 1:
result = df
elif n == 2 or n == 0:
df.append(1)
result = df
elif n % 2 == 0:
df.append(n/2)
df = sol(n/2, df)
else:
df_2 = df[:]
df_2 = df_2.append(n-1)
n_2 = n-1
df_2 = sol(n_2, df_2)
return df
df = []
n = input('n == ')
sol(n, df)
The error is as follow:
n == 3
Traceback (most recent call last):
File "Challenge_3_1_vTest.py", line 27, in <module>
solution(n)
File "Challenge_3_1_vTest.py", line 6, in solution
print((sol(n, df)))
File "Challenge_3_1_vTest.py", line 21, in sol
df_2 = sol(n_2, df_2)
File "Challenge_3_1_vTest.py", line 12, in sol
df.append(1)
AttributeError: 'NoneType' object has no attribute 'append'
The append function doesn't return a thing, that's why I was having the error and was passing a none when using number that are not power of 2.
df_2 = df_2.append(n-1)
This line of code was the source of the problem, I should have done:
df_2.append(n-1)

Python turtle: object has no attribute 'Turtle'

this is my code:
import turtle
e = turtle.Turtle
e.speed(10)
d = 100
angle = 140
for i in range (1, 1000):
e.forward(d)
e.left(angle)
d = d - 1
when i run the code and this thing pop up.
Traceback (most recent call last):
File "C:\Users\User\Desktop\Python\TUrtle graphic.py", line 2, in <module>
e = turtle.Turtle
AttributeError: 'module' object has no attribute 'Turtle'
Instead of:
e = turtle.Turtle
you need to do:
e = turtle.Turtle()
Full code:
import turtle
e = turtle.Turtle()
e.speed(10)
d = 100
angle = 140
for i in range(1, 1000):
e.forward(d)
e.left(angle)
d = d - 1
turtle.mainloop()
Note that d will eventually become negative so your forward will effectively become a backward for the majority of the iterations.

adding item in the dictionary coming from a list resulted in TypeError

this is the code:
import bisect
data = {'sal': 25000} # stored data from user input
table = {1249.99: 36.30, 1749.99: 54.50, 2249.99: 72.70, 2749.99: 90.80,
3249.99: 109.00, 3749.99: 127.20, 4249.99: 145.30, 4749.99: 163.50,
5249.99: 181.70, 5749.99: 199.80, 6249.99: 218.00, 6749.99: 236.20,
7249.99: 254.30, 7749.99: 272.50, 8249.99: 290.70, 8749.99: 308.80,
9249.99: 327.00, 9749.99: 345.20, 10249.99: 363.30, 10749.99: 381.50,
11249.99: 399.70, 11749.99: 417.80, 12249.99: 436.00, 12749.99:
454.20, 13249.99: 472.30, 13749.99: 490.50, 14249.99: 508.70,
14749.99: 526.80, 15249.99: 545.00, 15749.99: 563.20, 15750.00:
581.30}
# get corresponding value from the table
table_bisect = bisect.bisect(sorted(table), data['sal'])
if table_bisect >= 30:
table_bisect = 30
else:
table_bisect = table_bisect
s_table = sorted(table.value())
data['new'] = ''.join(s_table[table_bisect:(table_bisect+1)]
# TypeError: sequence item 0: expected string, float found
Everything works fine, until the last line, which return the error above. How can I fix the error or what are the work around?
It is because if you slice with list[index:index+1], it simply returns one value, which in this case is a float:
>>> y = [21, 4, 2, 5, 4, 3, 7, 9]
>>> y[5:6]
[3]
>>> ''.join(y[5:6])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>>
Instead, just do the following:
data['new'] = s_table[table_bisect:(table_bisect+1)][0]
Another option is to do this:
data['new'] = ''.join(str(s_table[table_bisect:(table_bisect+1)]))
the join() method expects string type if you need to use it.

Hi! am trying to make a conversational bot in python 2.7

import os,time
import random
import sys
namea = ['what is your name','whats your name','what is your name?','whats your name?']
greeta = ['hello','hi','hi there','hello there']
birth = ['what is your date of birth','what is your date of birth?','what is your DOB','what is your DOB?']
botmaster = ['who is your botmaster','who is your botmaster?','who is your father','who is your mother']
greetb = ['hi there','hello','hi my name is Ananymous','hello there']
nameb = ['I am called Ananymous','my name is Ananymous','I am called Ananymous']
K = '\n\n\n\n\n\n\n\n\n\n\n\n Ananymous \n\n onnline...........'
print(K)
while True:
C = raw_input('$').strip()
Cbot =C.bot()
if C == '':
print '$ Bye'
time.sleep(1)
os.system("sudo shutdown -h now")
break
elif Cbot in namea:
print '$' + (random.choice(nameb))
elif Cbot in greeta:
print '$' + (random.choice(greetb))
elif Cbot in botmaster:
print [('$ My botmaster Kumar')]
elif Cbot in birth:
print [('$ My Birthdate Is May 8 2017')]
C.bot()
This is my coding it throws an error like :
Traceback (most recent call last):
File "ananymous.py", line 16, in <module>
Cbot =C.bot()
AttributeError: 'str' object has no attribute 'bot'

Pynmea2 attribute error

I've been using the pynmea2 library, but today I ran a GPGGA message through it and it's throwing an attribute error when trying to access the objects datetime method.
>>> from pynmea2 import parse
>>> a = '$GPGGA,201326.000,3348.5072,N,11809.6409,W,2,20,0.55,37.5,M,-34.3,M,0000,0000*65'
>>> msg = parse(a)
>>> msg
<GGA(timestamp=datetime.time(20, 13, 26), lat='3348.5072', lat_dir='N', lon='11809.6409', lon_dir='W', gps_qual='2', num_sats='20', horizontal_dil='0.55', altitude=37.5, altitude_units='M', geo_sep='-34.3', geo_sep_units='M', age_gps_data='0000', ref_station_id='0000')>
>>> msg.datetime
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/pynmea2/nmea.py", line 154, in __getattr__
raise AttributeError(name)
AttributeError: datetime
Here's what line 154 and everything related states in nmea.py:
def __getattr__(self, name):
#pylint: disable=invalid-name
t = type(self)
try:
i = t.name_to_idx[name]
except KeyError:
raise AttributeError(name)
f = t.fields[i]
if i < len(self.data):
v = self.data[i]
else:
v = ''
if len(f) >= 3:
if v == '':
return None
return f[2](v)
else:
return v
Any ideas what this could be?
Thanks for looking at this!
Found it...GPGGA sentences have no date values in their string.
I think you want to access the timestamp attribute of the GPGGA record, using:
>>> from pynmea2 import parse
>>> a = '$GPGGA,201326.000,3348.5072,N,11809.6409,W,2,20,0.55,37.5,M,-34.3,M,0000,0000*65'
>>> msg = parse(a)
>>> msg
<GGA(timestamp=datetime.time(20, 13, 26), lat='3348.5072', lat_dir='N', lon='11809.6409', lon_dir='W', gps_qual='2', num_sats='20', horizontal_dil='0.55', altitude=37.5, altitude_units='M', geo_sep='-34.3', geo_sep_units='M', age_gps_data='0000', ref_station_id='0000')>
>>> msg.timestamp
datetime.time(20, 13, 26)