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'
Related
I have a bunch of code, Program is written in python2 and used old version of pymc. probably version2.x .
When i run
python run.py
the error i am facing
Init failure
Init failure
Init failure
Init failure
Init failure
Init failure
Init failure
Init failure
No previous MCMC data found.
Traceback (most recent call last):
File "run.py", line 106, in <module>
M=run_MCMC(ms)
File "run.py", line 94, in run_MCMC
mcmc = pm.MCMC(model, db=db, name=name)
File "/home/divyadeep/miniconda3/envs/detrital/lib/python2.7/site-packages/pymc/MCMC.py", line 90, in init
**kwds)
File "/home/divyadeep/miniconda3/envs/detrital/lib/python2.7/site-packages/pymc/Model.py", line 191, in init
Model.init(self, input, name, verbose)
File "/home/divyadeep/miniconda3/envs/detrital/lib/python2.7/site-packages/pymc/Model.py", line 92, in init
ObjectContainer.init(self, input)
File "/home/divyadeep/miniconda3/envs/detrital/lib/python2.7/site-packages/pymc/Container.py", line 605, in init
input_to_file = input.dict
AttributeError: 'NoneType' object has no attribute 'dict'`
I have tried to comment out some of 'init' in the program. but still not able to run.
the run.py is as
def InitExhumation(settings):
"""Initialize piece-wise linear exhumation model"""
#Check that erosion and age break priors are meaningful
if (settings.erate_prior[0] >= settings.erate_prior[1]):
print "\nInvalid range for erate_prior."
sys.exit()
if (settings.abr_prior[0] >= settings.abr_prior[1]):
print "\nInvalid range for abr_prior."
sys.exit()
#Create erosion rate parameters (e1, e2, ...)
e = []
for i in range(1,settings.breaks+2):
e.append(pm.Uniform("e%i" % i, settings.erate_prior[0], settings.erate_prior[1]))
#Create age break parameters (abr1, ...)
abr_i = settings.abr_prior[0]
abr = []
for i in range(1,settings.breaks+1):
abr_i = pm.Uniform("abr%i" % i, abr_i, settings.abr_prior[1])
abr.append(abr_i)
return e, abr
def ExhumationModel(settings):
"""Set up the exhumation model"""
#Check that error rate priors are meaningful
if (settings.error_prior[0] >= settings.error_prior[1]):
print "\nInvalid range for error_prior."
sys.exit()
err = pm.Uniform('RelErr',settings.error_prior[0],settings.error_prior[1])
#Closure elevation priors
hc_parms={'AFT':[3.7, 0.8, 6.0, 2.9], 'AHe':[2.2, 0.5, 3.7, 1.6]}
e, abr = InitExhumation(settings)
nodes = [err, e, abr]
hc = {}
for sample in settings.samples:
parms = e[:]
h_mu = np.mean(sample.catchment.z)
if sample.tc_type not in hc.keys():
hc[sample.tc_type] = pm.TruncatedNormal("hc_%s"%sample.tc_type, h_mu-hc_parms[sample.tc_type][0],
1/hc_parms[sample.tc_type][1]**2,
h_mu-hc_parms[sample.tc_type][2],
h_mu-hc_parms[sample.tc_type][3])
nodes.append(hc[sample.tc_type])
parms.append(hc[sample.tc_type])
parms.extend(abr)
if isinstance(sample, DetritalSample):
idx_i = pm.Categorical("Index_" + sample.sample_name, p = sample.catchment.bins['w'], size=len(sample.dt_ages))
nodes.extend([idx_i])
exp_i = pm.Lambda("ExpAge_" + sample.sample_name, lambda parm=parms, idx=idx_i: ba.h2a(sample.catchment.bins['h'][idx],parm))
value = sample.dt_ages
else:
idx_i = None
exp_i = pm.Lambda("ExpAge_" + sample.sample_name, lambda parm=parms: ba.h2a(sample.br_elevation,parm), plot=False)
value = sample.br_ages
obs_i = pm.Normal("ObsAge_" + sample.sample_name, mu = exp_i, tau = 1./(err*exp_i)**2, value = value, observed=True)
sim_i = pm.Lambda("SimAge_" + sample.sample_name, lambda ta=exp_i, err=err: pm.rnormal(mu = ta, tau = 1./(err*ta)**2))
nodes.extend([exp_i, obs_i, sim_i])
return nodes
def run_MCMC(settings):
"""Run MCMC algorithm"""
burn = settings.iterations/2
thin = (settings.iterations-burn) / settings.finalChainSize
name = "%s" % settings.model_name + "_%ibrk" % settings.breaks
attempt = 0
model=None
while attempt<5000:
try:
model = ExhumationModel(settings)
break
except pm.ZeroProbability, ValueError:
attempt+=1
#print "Init failure %i" % attemp
print "Init failure "
try:
#The following creates text files for the chains rather than hdf5
db = pm.database.txt.load(name + '.txt')
#db = pm.database.hdf5.load(name + '.hdf5')
print "\nExisting MCMC data loaded.\n"
except AttributeError:
print "\nNo previous MCMC data found.\n"
db='txt'
mcmc = pm.MCMC(model, db=db, name=name)
#mcmc.use_step_method(pm.AdaptiveMetropolis, M.parm)
if settings.iterations > 1:
mcmc.sample(settings.iterations,burn=burn,thin=thin)
return mcmc
if __name__ == '__main__':
sys.path[0:0] = './' # Puts current directory at the start of path
import model_setup as ms
if len(sys.argv)>1: ms.iterations = int(sys.argv[1])
M=run_MCMC(ms)
#import pdb; pdb.set_trace()
#Output and diagnostics
try:
ba.statistics(M, ms.samples)
except TypeError:
print "\nCannot compute stats without resampling (PyMC bug?).\n"
ps.chains(M, ms.finalChainSize, ms.iterations, ms.samples, ms.output_format)
ps.summary(M, ms.samples, ms.output_format)
ps.ks_gof(M, ms.samples, ms.output_format)
ps.histograms(ms.samples, ms.show_histogram, ms.output_format)
ps.discrepancy(M, ms.samples, ms.output_format)
## ps.unorthodox_ks(M, ms.output_format)
## try:
## ps.catchment(M.catchment_dem, format=ms.output_format)
## except KeyError:
## print "\nUnable to generate catchment plot."
M.db.close()
`
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)
I'm a newbie to Python and started playing with NLTK this evening.
I've read in a file with pandas and now trying to call one column, the description. I'm hitting a problem with the code because it was originally written to call a bit of text in script.
I've tried to amend it but think I've broken it. Code and errors below
import nltk
import pandas as pd
data = pd.read_csv("data.csv", sep=",")
#data.head()
datatext = data['Description']
#datatext.head()
import nltk
from nameparser import HumanName
#nltk.download()
def get_human_names(datatext):
tokens = nltk.tokenize.word_tokenize(datatext.read())
pos = nltk.pos_tag(tokens)
sentt = nltk.ne_chunk(pos, binary = False)
person_list = []
person = []
name = ""
for subtree in sentt.subtrees(filter=lambda t: t.node == 'PERSON'):
for leaf in subtree.leaves():
person.append(leaf[0])
if len(person) > 1: #avoid grabbing lone surnames
for part in person:
name += part + ' '
if name[:-1] not in person_list:
person_list.append(name[:-1])
name = ''
person = []
return (person_list)
text = datatext
names = get_human_names(datatext)
print "LAST, FIRST"
for name in names:
last_first = HumanName(name).last + ', ' + HumanName(name).first
print last_first
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-18-2f6ec1c0b04c> in <module>()
21 text = datatext
22
---> 23 names = get_human_names(datatext)
24 print "LAST, FIRST"
25 for name in names:
<ipython-input-18-2f6ec1c0b04c> in get_human_names(datatext)
1 def get_human_names(datatext):
----> 2 tokens = nltk.tokenize.word_tokenize(datatext.read())
3 pos = nltk.pos_tag(tokens)
4 sentt = nltk.ne_chunk(pos, binary = False)
5 person_list = []
C:\Anaconda2\lib\site-packages\pandas\core\generic.pyc in __getattr__(self, name)
2358 return self[name]
2359 raise AttributeError("'%s' object has no attribute '%s'" %
-> 2360 (type(self).__name__, name))
2361
2362 def __setattr__(self, name, value):
AttributeError: 'Series' object has no attribute 'read'
I was scraping Yahoo finance and somehow the if condition did not work. What the if was supposed to do was to print the stock price if the stock price was greater than 50, but it printed all the stocks which were above 50 and below 50.
Here is the code:
import urllib2
from bs4 import BeautifulSoup as bs4
list = ["aapl","goog","yhoo"]
i = 0
while i < len(list):
url = urllib2.urlopen("http://finance.yahoo.com/q?s="+ list[i] +"&q1=1")
soup = bs4(url,"html.parser")
for price in soup.find(attrs={'id':"yfs_l84_" + list[i]}):
if price > 50:
print price
i += 1
else:
print "failed"
1 += 1
Why did it print the stock "yahoo", cause "yahoo" is less than 50, no?
We can rewrite code in following:
1 += 1 will not work because LHS should be variable name. This is i += 1 . this might be typing mistake. :)
No need of i variable, we can iterate list by for loop. This will remove our i += 1 statements from the code.
Do not use in-built variable names as our variable names. e.g. list is list type variable used to create new list. If we use such variable name then this will create problem in code.
e.g.
>>> list
<type 'list'>
>>> a = list()
>>> a
[]
>>> list = [1,2,3,4]
>>> a = list()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>>
Use exception handling during Type Casting means when we convert one data type to other data type.
Demo:
import urllib2
from bs4 import BeautifulSoup as bs4
item_list = ["aapl","goog","yhoo"]
target_url = "http://finance.yahoo.com/q?s=%s&q1=1"
target_id = "yfs_l84_%s"
for i in item_list:
url = urllib2.urlopen(target_url%i)
soup = bs4(url, "html.parser")
for price in soup.find(attrs={'id':target_id%i}):
try:
price = float(price)
except:
print "Exception during type conversion. Value is %s. Type is %s."%(price, type(price))
continue
if price > 50:
print "Price:", price
else:
print "failed"
Seems to me you've mixed types:
if price > 50:
TypeError: unorderable types: NavigableString() > int()
Use this:
if float(price) > 50:
print price
price is string, you have to convert it to number:
if int(price) > 50:
print price
i += 1
else:
print "failed"
i += 1
or (with fractional part):
if float(price) > 50:
print price
i += 1
else:
print "failed"
i += 1
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)