How to replace email domain misspellings - python

I manage a booking system where people enter their emails to book appointments. Unfortunately, many of the email addresses have typos, especially in the top-level domain. I'd like to implement a function to identify when the domain should be .com, which should be all cases where it starts with ".c".
I wrote the function and tested the individual lines, which seem to work. But when I run the function on a set of emails, it only returns the email with no ".c", meaning it only returns 'my_name_is#orange.org'. The ideal output would be:
['me.you#perp.com',
'appleorange#msn.edu.com',
'laughable#gmail.com',
'notfunny#pointdexter.com',
'very.latin...word#word.nutherwork.com',
'very.latin..word#word.nutherwork.com',
'my_name_is#orange.org']
Any help would be appreciated!
emails = ['me.you#perp.comp',
'appleorange#msn.edu.cot',
'laughable#gmail.copl',
'notfunny#pointdexter.com',
'very.latin...word#word.nutherwork.com',
'very.latin..word#word.nutherwork.cnm',
'my_name_is#orange.org']
def domain(emails):
for email in emails:
parse_mail = email.split('.')
parse_mail = parse_mail[-1]
if parse_mail[0] == "c":
email = email.replace(parse_mail,"com")
pass
return email
print(domain(emails))

It returns the email without "c" because that's the last one in the array.
Your routine "domain" only returns the last email in the array. If you put the org address higher up, it'll return an email with a "c".

I expect what you're looking for is:
def domain(emails):
for i in range(len(emails)):
parse_mail = emails[i].split('.')
if parse_mail[-1][0] == "c":
parse_mail = emails[i].split('.')[:-1]
parse_mail.append("com")
correct = '.'.join(parse_mail)
emails[i] = correct
pass
return emails
print(domain(emails))
But as Sembei Norimaki, mentioned - this will also auto-correct (erroneously) other extensions beginning with a 'c'.

Related

How do I make a 'properly formatted HTML link for an email address'?

I am in a computer science class. I was just given this assignment today. It was completely blank spare a docstring at the top.
'''
Write a function that returns a properly formatted HTML link for
an email address.
Uber Geek Option:
Include code that checks to see if the email itself is properly formatted
Hacker Option:
Also include code that checks to see if the email is valid
'''
How do I begin this? I have tried sites such as WikiHow and RealPython. This may be an information error, but I am sure my teacher wrote what he meant in this assignment.
EDIT: I fixed most of the code, but I cannot get it to understand and replace the inputted email with the emAdd variable.
import re
def isvalidEmail(email):
pattern = "^\S+#\S+\.\S+$"
objs = re.search(pattern, email)
try:
if objs.string == email:
return True
except:
return False
def emailAddress():
emAdd = input("Enter your email address: ")
if ('#' and '.') and ('.net' or '.com') not in emAdd:
print("Enter a properly formatted email address.")
emailAddress()
else:
cke = isvalidEmail(emAdd)
if cke == True:
print('<a href="mailto:'+emAdd+'?">')
else:
print("enter a valid email.")
emailAddress()
put_me_in_another_file = '<a href="mailto:'+emAdd+'?">'
emailAddress()
file = open("email.html","w")
# Adding input data to the HTML file
file.write("<html>\n<head>\n<title> \nYour Email in A Webpage \
</title>\n</head> <body><h1>Welcome to <u>Your Email</u></h1>\
\n<h2>A hyperlink to send emails to the inputted email should appear below.</h2><a href=mailto:emAdd?>\n</body></html>")
# Saving the data into the HTML file
file.close()

How to get a single valid email address out of 20 obfuscated email addresses using Python

I would like to decode the email.
Input:
obfuscated_email_addresses_raw = '''hknrnajuw#moulcgs.net, oituugim#jdcq.net, woecfsgyu#ynjbghrj.edu, yabygip#qmqmulu.edu, ysio#ydok.org, gbpum#bccds.edu, onmfy#uomiuju.org, hfujlo#rorthqgn.gov, nkhpanbya#tsngmfe.net, michael#hmblawoffice.com, pojesgpu#ypkqgti.net, fatuqwh#tmaqnggr.org, wqlpij#jeyfe.gov, abww#wjy.gov, unhdj#mroi.com, nhaw#qoh.com, iljqin#cehh.edu, mdsidnsok#ilnf.gov, jpofhqa#qyigalj.org, qwwlpfwe#ldrph.org'''
list_of_obfuscated_email_addresses = [i.strip() for i in w.split(',')]
print(len(list_of_obfuscated_email_addresses))
From above code, we can see there is only one email address which turns out to be valid, that is michael#hmblawoffice.com.
Is there any way to get only one valid email out of obfuscated email using Python?
EXPECTED OUTPUT:
michael#hmblawoffice.com
Thanks ahead!

Google app engine - Order listed item

I need your help to order listed item.
I am trying to make apps that can send message to his/her friends ( just like social feeds ). After watching Bret Slatkin talk about create microblogging here's my code:
class Message(ndb.Model):
content = ndb.TextProperty()
created = ndb.DateTimeProperty(auto_now=True)
class MessageIndex(ndb.Model):
receivers = ndb.StringProperty(repeated=True)
class BlogPage(Handler):
def get(self):
if self.request.cookies.get("name"):
user_loggedin = self.request.cookies.get("name")
else:
user_loggedin = None
receive = MessageIndex.query(MessageIndex.receivers == user_loggedin)
receive = receive.fetch()
message_key = [int(r.key.parent().id()) for r in receive]
messages = [Message.get_by_id(int(m)) for m in message_key]
for message in messages:
self.write(message)
The first I do a query to get all message that has my name in the receivers. MessageIndex is child of Message, then I can get key of all message that I receive. And the last is I iter get_by_id using list of message key that I get.
This works fine, but I want to filter each message by its created datetime and thats the problem. The final output is listed item, which cant be ordered using .order or .filter
Maybe some of you can light me up.
You can use the message keys in an 'IN' clause in the Message query. Note that you will need to use the parent() key value, not the id() in this case.
eg:
# dtStart, dtEnd are datetime values
message_keys = [r.key.parent() for r in receive]
query = Message.query(Message._key.IN(message_keys), Message.created>dtStart, Message.created<dtEnd)
query = query.order(Message.created) # or -Message.created for desc
messages = query.fetch()
I am unsure if you wish to simply order by the Message created date, or whether you wish to filter using the date. Both options are catered for above.

Get author_id from mail_message in openERP

I'm trying to get a field from openERPs mail_message model using python code which is executed in a server action (so its not a module where I can debug! I cannot even print in this state) (when a new eMail is being fetched) but I am unable to get anything useful from it.
Basicly when someone is throwing me a email, a new Task is created by openERP. But the newely created ticket is not connected to the user which send me the mail.
When a new email is fetched, this server action gets executed.
In a table called mail_message you can then find the email (+ author_id, + email, + res_id (which is the id of the created Task), therefore I'd like to fetch the author_id from that table.
(A query would look like this:
SELECT author_id FROM mail_message WHERE type = 'email' AND res_id = '<Task.id>')
This is my current code
#Initialize object. That one points to the mail_message model.
mailMessage_obj = self.pool.get('mail.message')
#Created Id in project_task
myId = object.id
#browse whole object with that id
#message = mailMessage_obj.browse(cr,uid,[myId])
#Select field where
messageIds = mailMessage_obj.search(cr,uid,[('type','=','email'),('res_id','=',myId)],context=context)
if messageIds:
#messageRecord = mailMessage_obj.browse(cr,uid,[myId],context=context)
#object.write({'partner_id':messageRecord.author_id.id})
res = mailMessage_obj.read(messageIds, ['author_id'])
partnerId = res[0]
#Author id
#partnerId = message[0]['author_id']
#partnerId = message.author_id
#res = [(r['id'], r['author_id']) for r in messageRecord]
#partnerId = res
#partnerId = 259866
object.write({'partner_id':partnerId})
I dont know how to get my hands on the author_id properly. If I hardcode a ID and let it write to the database (last two lines) It'll work just fine, but I cant hardcode a users id. ;)
Could someone explain to me how its done correctly?
I dont know whether I should use .browse or .read or something else..
I think you have an error on you python method.
you wrote :
res = mailMessage_obj.read(messageIds, ['author_id'])
partnerId = res[0]
But read() method returns here a list of dict (because messageIds is a list). Then, you have not specified the field you wanted to retrieve from res variable, and finally, as author_id is a many2one, it returns something like this : (2, 'myusers').
You should have done :
res = mailMessage_obj.read(cr, uid, messageIds, ['author_id'])
partnerId = res[0]['author_id'][0]
Hope i helped you,
Greatings

Asking for inputs in my script [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to prompt the user to input number of users to run and email addresses to populate a csv file. I am getting some syntax error. How do I get this working ?
enter code here
import csv
# Define users
valid_input = False
while not valid_input:
users =raw_input('Number of users: ')
try:
users = range(0,int(users)
valid_input = True
except:
print "Invalid input"
pass
First_Name = ["Test"+str(user) for user in range(1, users+1)]
Last_Name = ["User%s" %user for user in users]
email_addresses = []
for user in users:
email= raw_input("Email domain for user %d: " %user)
email_addresses.append(last_names[user] + email)
Password = ["Password1" for user in users]
Group =["Test" for user in users]
Admin = ["Yes" for user in users]
# open a file for writing.
# open a file for writing.
with open('users.csv', 'wb') as csv_out:
writer = csv.writer(csv_out)
writer.writerows(zip(Email_Address, Password, First_Name, Last_Name, Group, Admin))
The line
Email_Address = (raw_input('Email_Address') [Last_Names + "Email_Address " for Last_Names inLast_Name]])
is invalid syntax. It's actually very difficult to tell what you're trying to do with that line, but it is very invalid syntax.
Also you seem to be misunderstanding iteration in python. On your first line you prompt for a single number and then try to iterate through it in multiple other places, which I'm guessing is pretty far from your intention.
users = (raw_input('number of users'))
will set users equal to a single string. I'm guessing that what you'd actually want is something more like this:
valid_input = False
while not valid_input:
users =raw_input('Number of users: ')
try:
users = range(0,int(users))
valid_input = True
except:
print "Invalid input"
pass
I've been reading through the code some more and while it seems to be pretty far from what you've written there, I'm guessing that you want to prompt the user for an email address for each user. If that is indeed the case, this is how you would do it:
email_addresses = []
for user in users:
email = raw_input("Email address for user %d: " %user)
email_addresses.extend([email + last_name for last_name in last_names])
Apparently I was mistaken about your intent, here's a solution for what you're looking for:
email_addresses = []
for user in users:
email= raw_input("Email domain for user %d: " %user)
email_addresses.append(last_names[user] + email)
Also, a couple style notes:
Try to keep all of your variable names as descriptive as possible. For instance, the last_name list you've got doesn't actually have last names, but holds user ids, so user_ids would be a better name
If you are going to adopt a pluralization nomenclature then make sure to pluralize lists and then make sure that the items can be referenced as the singular version instead of the other way around. For example:
last_name = [#some list]
[#something for last_names in last_name]
is just confusing. It should be:
last_names = [#some_list]
[#something for last_name in last_names]
Choose either snake case (like_this) or title case (likeThis) and stick with it. Nothing is more annoying than having to scroll through a lost codebase and figure out which case a particular variable is using.
I'm not into Python at all, but it seems to be 1 square bracket too much at the end of this line :
Email_Address = (raw_input('Email_Address') [Last_Names + "Email_Address " for Last_Names inLast_Name]])
After this line:
users = (raw_input('number of users'))
users is a string. Let's say you enter 100.
Now, you iterate over users:
First_Name = ["Test"+str(user) for user in users]
Strings are iterable, so user takes on the individual characters of the string '100'. That is, user will first be '1', then '0', then '0' again; you get Test1 then Test0 then Test0 rather than the 100 items I expect you expect.
You probably want to convert the input to an integer:
users = int(raw_input('number of users'))
And then iterate over a range (I'm assuming you want 1 through n rather than 0 through n-1:
First_Names = ["Test"+str(user) for user in range(1, users+1)]
I've also taken the liberty of changing the name of your variable to First_Names as what you have is a list of the first names, not a single first name.
Unfortunately, I don't really have the time to go into the rest of the problems with your code, of which there are many (including the question about input that you're actually asking), but that ought to get you started fixing it up.

Categories

Resources