Disclaimer: I'm trying to write one of my first classes in python, so please make any criticism constructive please.
#!/usr/bin/python
from optparse import OptionParser
class Permutate:
email_dict = {}
email_provider = (
'#gmail.com',
'#aol.com',
'#yahoo.com'
)
def __init__(self, fname, lname):
'''
vars:
[fname] - first name of the permutation
[lname] - last name of the permutation
[email_combination] - first and last name
'''
self.fname = fname
self.lname = lname
self.email_combination = email_combination
'''
compute_first_last():
email_combination = <string> + <string> + <string>
computes the first name and last name combination plus and email provider.
Loop through all combinations of first + last + email_provider while the value *is u
A single combination looks like <fname>.<lname>#<email_provider>
Thank you
After the revisions to the question, this is a working piece of code that will give you output. Not sure if it is exactly what you want, but it will work.
#!/usr/bin/python
from optparse import OptionParser
class Permutate:
email_dict = {}
email_provider = (
'#gmail.com',
'#aol.com',
'#yahoo.com'
)
def __init__(self, fname, lname):
'''
vars:
[fname] - first name of the permutation
[lname] - last name of the permutation
[email_combination] - first and last name
'''
assert isinstance(fname, str) and isinstance(lname, str), "Only strings may be supplied as names"
self.fname = fname
self.lname = lname
self.email_combination = fname + "." + lname
for provider in Permutate.email_provider:
print "%s%s" % (self.email_combination, provider)
def compute_first_last():
'''
compute_first_last():
email_combination = <string> + <string> + <string>
computes the first name and last name combination plus and email provider.
Loop through all combinations of first + last + email_provider while the value *is u
A single combination looks like <fname>.<lname>#<email_provider>
'''
parser = OptionParser(usage='%prog -f fname -l lname', version='%prog 1.1')
parser.add_option('-f', '--fname', dest='fname')
parser.add_option('-l', '--lname', dest='lname')
(opt, args) = parser.parse_args()
perm = Permutate(opt.fname, opt.lname)
if __name__ == '__main__':
compute_first_last()
The optparse library is fairly convenient for accepting command line arguments in Python.
For more information, take a look at:
https://docs.python.org/2/library/optparse.html
You can accept command line arguments similar to that below:
from optparse import OptionParser
def main():
parser = OptionParser(
usage='%prog -f firstname -l lastname',
version='%prog 1.1')
parser.add_option('-f', '--firstname', dest='firstname')
parser.add_option('-l', '--lastname', dest='lastname')
(opt, args) = parser.parse_args()
print opt.firstname
print opt.lastname
# You can create the new Permutate object here
# perm = Permutate(opt.firstname, opt.lastname)
# and call its relevant functions
if __name__ == '__main__':
main()
The results you will get will look like:
python myfile.py -f firstnamehere -l lastnamehere
firstnamehere
lastnamehere
Note: You should also perform input sanitation to ensure that the user is calling the script correctly.
I believe this section and the method compute_first_last():
if __name__ == '__compute_first_last__':
compute_first_last()
should not be within the scope of the Class permutate, which it currently is. Edit: Also, and this part I deleted previously but forgot to re-include, this should actually say:
if __name___ == '__main__':
compute_first_last()
Currently all the interpreter is doing is parsing a file containing a Class. It is missing the execution of the method you want, because it is contained within the class and never called explicitly. Also, you are calling the method compute_first_last supplying no parameters, although it is expecting four. You can take it from here! :-)
Edit: Explanation on how/what this does: What does if __name__ == "__main__": do?
Edit: having checked your code again, I've edited the above.
#!/usr/bin/python
from optparse import OptionParser
class Permutate:
email_dict = {}
email_provider = (
'#gmail.com',
'#aol.com',
'#yahoo.com'
)
def __init__(self, fname, lname):
'''
vars:
[fname] - first name of the permutation
[lname] - last name of the permutation
[email_combination] - first and last name
'''
self.fname = fname
self.lname = lname
self.email_combination = email_combination
'''
compute_first_last():
email_combination = <string> + <string> + <string>
computes the first name and last name combination plus and email provider.
Loop through all combinations of first + last + email_provider while the value *is u
A single combination looks like <fname>.<lname>#<email_provider>
'''
def compute_first_last(self, fname, lname, email_combination):
parser = OptionParser(usage='%prog -f fname -l lname', version='%prog 1.1')
parser.add_option('-f', '--fname', dest='fname')
parser.add_option('-l', '--lname', dest='lname')
(opt, args) = parser.parse_args()
perm = Permutate(opt.fname, opt.lname)
email_combination = fname + "." + lname + email_provider
while combination in email_combination:
print combination
if __name__ == '__main__':
compute_first_last() #this method call needs to be provided parameters
Related
I want to make R datatype to Python datatype below is the whole code
def convert_datafiles(datasets_folder):
import rpy2.robjects
rpy2.robjects.numpy2ri.activate()
pandas2ri.activate()
for root, dirs, files in os.walk(datasets_folder):
for name in files:
# sort out .RData files
if name.endswith('.RData'):
name_ = os.path.splitext(name)[0]
name_path = os.path.join(datasets_folder, name_)
# creat sub-directory
if not os.path.exists(name_path):
os.makedirs(name_path)
file_path = os.path.join(root, name)
robj = robjects.r.load(file_path)
# check out subfiles in the data frame
for var in robj:
###### error happend right here
myRData = pandas2ri.ri2py_dataframe( var )
####error happend right here
# convert to DataFrame
if not isinstance(myRData, pd.DataFrame):
myRData = pd.DataFrame(myRData)
var_path = os.path.join(datasets_folder,name_,var+'.csv')
myRData.to_csv(var_path)
os.remove(os.path.join(datasets_folder, name)) # clean up
print ("=> Success!")
I want to make R datatype to pythone type, but the error keeps popping up like this : AttributeError: 'str' object has no attribute 'dtype'
How should I do to resolve this error?
The rpy2 documentation is somewhat incomplete when it comes to interaction with pandas, but unit tests will provide examples of conversion. For example:
rdataf = robjects.r('data.frame(a=1:2, '
' b=I(c("a", "b")), '
' c=c("a", "b"))')
with localconverter(default_converter + rpyp.converter) as cv:
pandas_df = robjects.conversion.ri2py(rdataf)
I am having troubles with my money variable. Each time I save and run, a ERROR pops up and I try to fix the problem but can't figure out how? I really need a reply so please soon. This is my project:
money = 0.0
Chop = 0
spike = 0
name = input("What is your name?")
greeting = 'Hello ' + name + ','
def Command():
Command = input('Press \"C\" to continue or Press \"E\" to exit -->')
if name == 'SpikeTheKing':
print('Welcome Spike,')
spike = 1
elif name == 'Spike':
spike = 1
print ('Welcome Spike,')
else:
print(greeting)
def draw_line():
print ('----------------')
def Work1():
Chop = input('Type anything to earn $1 -->')
while Chop == ('C') or ('c'):
print ('$1 earned')
money = money+1
displayMoney()
Chop = 0
Command()
def displayMoney():
draw_line()
print(('Money = '),('$'),(money))
draw_line()
displayMoney()
Work1()
if Command == ('C'):
Work1()
if Command == ('E'):
quit()
Each time I save and run this happens:
Traceback (most recent call last):
File "C:\Users\Leora\Desktop\Python Files\Python.py", line 35, in <module>
Work1()
File "C:\Users\Leora\Desktop\Python Files\Python.py", line 26, in Work1
money = money+1
UnboundLocalError: local variable 'money' referenced before assignment
What should I change?
In the def Work code, before you do money = money+1, you will need to initialize money. So in the first statement after def Work, do: money = 0...
Alternatively, money is global , so you could do global money, in the first line after def Work instead of money=0....
The global keyword tells the interpreter, that money is defined outside the scope of Work function and to look for it there
I Have a Script for data extraction from some CSV files and bifurcating the Data into different excel files. I using Ipython for the that and I m sure it using CPython as the Default interpreter.
But the script is taking too much time for the whole process to finish. Can someone please help to how use that script using the PyPy as i heard it is much faster than CPython.
Script is something like this:
import pandas as pd
import xlsxwriter as xw
import csv
import pymsgbox as py
file1 = "vDashOpExel_Change_20150109.csv"
file2 = "vDashOpExel_T3Opened_20150109.csv"
path = "C:\Users\Abhishek\Desktop\Pandas Anlaysis"
def uniq(words):
seen = set()
for word in words:
l = word.lower()
if l in seen:
continue
seen.add(l)
yield word
def files(file_name):
df = pd.read_csv( path + '\\' + file_name, sep=',', encoding = 'utf-16')
final_frame = df.dropna(how='all')
file_list = list(uniq(list(final_frame['DOEClient'])))
return file_list, final_frame
def fill_data(f_list, frame1=None, frame2=None):
if f_list is not None:
for client in f_list:
writer = pd.ExcelWriter(path + '\\' + 'Accounts'+ '\\' + client + '.xlsx', engine='xlsxwriter')
if frame1 is not None:
data1 = frame1[frame1.DOEClient == client] # Filter the Data
data1.to_excel(writer,'Change',index=False, header=True) # Importing the Data to Excel File
if frame2 is not None:
data2 = frame2[frame2.DOEClient == client] # Filter the Data
data2.to_excel(writer,'Opened',index=False, header=True) # Importing the Data to Excel File
else:
py.alert('Please enter the First Parameter !!!', 'Error')
list1, frame1 = files(file1)
list2, frame2 = files(file2)
final_list = set(list1 + list2)
Lex file
import ply.lex as lex
# List of token names.
tokens = (
"SYMBOL",
"COUNT"
)
t_SYMBOL = (r"Cl|Ca|Co|Os|C|H|O")
def t_COUNT(t):
r"\d+"
t.value = int(t.value)
return t
def t_error(t):
raise TypeError("Unknown text '%s'" % (t.value,))
atomLexer = lex.lex()
data1 = "CH3Cl"
data = "OClOsOH3C"
def testItOut():
# Give the lexer some input
atomLexer.input(data1)
# Tokenize
tok = atomLexer.token()
while tok:
print (tok)
tok = atomLexer.token()
Parse file
import ply.yacc as yacc
# Get the token map from the lexer.
from atomLex import tokens
def p_expression_symbol(p):
'molecule : SYMBOL'
p[0] = p[1]
def p_error(p):
raise TypeError("unknown text at %r" % (p.value,))
atomParser = yacc.yacc()
def testItOut():
# Give the parser some input
s = input('Type a chemical name > ')
# Parse it
result = atomParser.parse(s)
print ('The atom is: ' + result)
while(True):
testItOut()
Currently I would like to be able to enter in CH3Cl, although within my parse file I am not entirely sure how to create these grammar definitions that I have been given,
chemical : chemical molecule
chemical : molecule
molecule : SYMBOL COUNT
molecule : SYMBOL
What would the grammar definitions for these be within the parse file? Thank you.
There is a nice set of documentation for PLY with examples, which can be used to answer this question: http://www.dabeaz.com/ply/ply.html
Section 6.2 is particularly helpful. I suggest you change this code:
def p_expression_symbol(p):
'molecule : SYMBOL'
p[0] = p[1]
To include the new rules. The name p_expression_symbol is also inappropriate. I guess you copied that from one of the examples. We now have:
def p_chemical_forumal(p):
'''molecule : SYMBOL
chemical : chemical molecule
chemical : molecule
molecule : SYMBOL COUNT
molecule : SYMBOL'''
p[0] = p[1]
There are also other useful examples in the documentation that can be applied to your exercise.
In python 3 I have a line asking for input that will then look in an imported dictionary and then list all their inputs that appear in the dictionary. My problem is when I run the code and put in the input it will only return the last word I input.
For example
the dictionary contains (AIR, AMA)
and if I input (AIR, AMA) it will only return AMA.
Any information to resolve this would be very helpful!
The dictionary:
EXCHANGE_DATA = [('AIA', 'Auckair', 1.50),
('AIR', 'Airnz', 5.60),
('AMP', 'Amp',3.22),
The Code:
import shares
a=input("Please input")
s1 = a.replace(' ' , "")
print ('Please list portfolio: ' + a)
print (" ")
n=["Code", "Name", "Price"]
print ('{0: <6}'.format(n[0]) + '{0:<20}'.format(n[1]) + '{0:>8}'.format(n[2]))
z = shares.EXCHANGE_DATA[0:][0]
b=s1.upper()
c=b.split()
f=shares.EXCHANGE_DATA
def find(f, a):
return [s for s in f if a.upper() in s]
x= (find(f, str(a)))
toDisplay = []
a = a.split()
for i in a:
temp = find(f, i)
if(temp):
toDisplay.append(temp)
for i in toDisplay:
print ('{0: <6}'.format(i[0][0]) + '{0:<20}'.format(i[0][1]) + ("{0:>8.2f}".format(i[0][2])))
Ok, the code seems somewhat confused. Here's a simpler version that seems to do what you want:
#!/usr/bin/env python3
EXCHANGE_DATA = [('AIA', 'Auckair', 1.50),
('AIR', 'Airnz', 5.60),
('AMP', 'Amp',3.22)]
user_input = input("Please Specify Shares: ")
names = set(user_input.upper().split())
print ('Listing the following shares: ' + str(names))
print (" ")
# Print header
n=["Code", "Name", "Price"]
print ('{0: <6}{1:<20}{2:>8}'.format(n[0],n[1],n[2]))
#print data
for i in [data for data in EXCHANGE_DATA if data[0] in names]:
print ('{0: <6}{1:<20}{2:>8}'.format(i[0],i[1],i[2]))
And here's an example of use:
➤ python3 program.py
Please Specify Shares: air amp
Listing the following shares: {'AMP', 'AIR'}
Code Name Price
AIR Airnz 5.6
AMP Amp 3.22
The code sample you provided actually does what was expected, if you gave it space separated quote names.
Hope this helps.