Python - using Regex findall strings after some fixed text - python

I'm new to Python and am getting confused. I have a list of email strings and want to get the string after some specific text and before some text. So from the list below;
Email: promo#madeup.com
Email: dave#madeup.com
Email: john#madeup.com
get the following;
promo#madeup
dave#madeup
john#madeup
I've managed to get the first string (below) but can't seem to get all of them
import re
lines = '''
Email: promo#madeup.com
Email: dave#madeup.com
Email: john#madeup.com
'''
emailAddr = lines.split('Email:')[1] #start
emailAddr2 = emailAddr.split('.com')[0] #end
print(emailAddr2)

Use a lookbehind to match the Email: prefix before each email and the .com suffix.
emails = re.findall(r'(?<=Email: ).*(?=\.com)', lines)
print(emails)
Or just loop through the lines and remove the Email: prefix.
emails = [s.replace('Email: ', '').replace('.com') for s in lines.splitlines() if s]
print(emails)

lines = '''
Email: promo#madeup.com
Email: dave#madeup.com
Email: john#madeup.com
'''
lines = lines.split('\n')
output = [x.split('Email:')[1].replace('.com','').strip() for x in lines if 'Email:' in x]
print(output)
will output:
['promo#madeup', 'dave#madeup', 'john#madeup']
if you want them all printed on a new line:
print('\n'.join(output))
will output:
promo#madeup
dave#madeup
john#madeup

Related

How to split an email in Python after '#'?

I have this piece of code but when you insert an email, the domain does not print fully. Can someone please explain what is wrong with the code and if there is a faster option? (I am new to Python)
email = input ('Enter your email address: ').strip()
at = email.find ('#')
after_at = email.find (' ' , at)
host = email [at+1 : after_at]
print (host)
Ex. abc#gmail.com > gmail.co
You should be able to use str.split:
domain = email.split('#')[-1]

How to separate a command from the rest of the message in telegram bots with pyTelegramBotAPI?

For example in the following command
/set first_name, last_name
How to separate or remove /set from the rest of the message?
Since commands can use only latin letters, numbers and underscores, you can separate it with the tiny regular expression, like this:
import re
pattern = "^\/[a-zA-Z\d_]* (.*)$"
string = "/set first_name, last_name"
match = re.match(command_pattern , string)
message = match.group(1)
# first_name, last_name
Another solution:
string = "/set first_name, last_name"
message = " ".join(string.split(" ")[1:])
# first_name, last_name
But the limitation of the last method is that it removes double spaces from the string if they existed.

Splitting a multi-word string into two variables

I have a document that holds login details as "username1, password1, username2, password2 etc." Is there a way of splitting them into two arrays that hold just usernames and just passwords?
I tried doing: usernames, passwords = login.split(",") but that's just a ValueError.
Sorry if it's something so obvious!
Update:
login = "username1, password1, username2, password2"
you are getting ValueError because login.split() returns a list with more than two elements.
If your data are formatted as username, password you can split and then slice the list:
login = "username1, password1, username2, password2"
data = login.split(",")
usernames = data[::2]
passwords = data[1::2]
My solution works on even and odd index of a list. If even index, then append to usernames, if odd index then to passwords.
login='username1, password1, username2, password2'
usernames, passwords = [], []
s = login.split(",")
for i in range(len(s)):
usernames.append(s[i]) if i%2 == 0 else passwords.append(s[i])
i believe you have the file structure like below:
username1, password1, username2, password2
username3, password3, username4, password4
username5, password5, username6, password6
username7, password7, username8, password8
then the below code will work ,
import csv
list_username=[]
list_pwd=[]
with open("untitled.txt") as f1:
csvrow=csv.reader(f1,delimiter=",")
for row in csvrow:
usernames = row[0] + "," +row[2]
passwords = row[1] + "," +row[3]
list_username.append(usernames)
list_pwd.append(passwords)
print(list_username)
print(list_pwd)
i have attached the output of the code as well,

How to pull specific parts of a list on each line?

I have a list that spits out information like this: ['username', 'password'], ['username', 'password'], ['username', 'password'], and so on..
I would like to be able to pull a specific username and password later on.
For example:
['abc', '9876'], ['xyz', '1234']
pull abc and tell them the password is 9876.
Then pull xyz and tell them the password is 1234
I tried messing around with the list and I am just drawing a blank on how to do this.
lines = []
with open("output.txt", "r") as f:
for line in f.readlines():
if 'Success' in line:
#get rid of everything after word success so only username and password is printed out
lines.append(line[:line.find("Success")-1])
for element in lines:
#split username and password up at : so they are separate entities
#original output was username:password, want it to be username, password
parts = element.strip().split(":")
print(parts)
I want to pull each username and then pull their password as described above
Current output after running through this is ['username', 'password']. The original output file had extra information that I got rid of which is what the code involving 'Success' took care of
I would like to do this without hardcoding a username in to it. I am trying to automate this process so that it runs through every username and formats it to say, "hi [username}, your password is [123]", for all of the usernames
I then later would like to be able to only tell the specific user their password. For example, i want to send an email to user abc. that email should only contain the username and password of user abc
Instead of printing parts, append them to a list.
data = []
for element in lines:
parts = element.strip().split(":")
data.append(parts)
Then you could convert these into a dictionary for lookup
username_passwords = dict(data)
print(username_passwords['abc'])
If I am understanding this correctly parts is the list that contains [Username:Password]. If that is the case we can assign each value of parts which should only have 2 elements in it to a dictionary as a dictionary pair and then call the username later on.
lines = []
User_Pass = {}
with open("output.txt", "r") as f:
for line in f.readlines():
if 'Success' in line:
#get rid of everything after word success so only username and password is printed out
lines.append(line[:line.find("Success")-1])
for element in lines:
#split username and password up at : so they are separate entities
parts = element.strip().split(":")
User_Pass.update({parts[0] : parts[1]})
Then you can call the password from the username as follows if you know the username:
x = User_Pass["foo"]
Or as you stated in the comments:
for key, value in User_Pass.items():
print('Username ' + key + ' Has a Password of ' + value)
it looks like after you do this
lines.append(line[:line.find("Success")-1])
lines = ['username:password', 'username:password'...]
so I would do this
new_list_of_lists = [element.strip().split(":") for element in lines]
new_list_of_lists should now look like [[username, password], [username, password]]
then just do this:
dict_of_usernames_and_passwords = dict(new_list_of_lists)
with a dict you can have now retrieve passwords using usernames. like:
dict_of_usernames_and_passwords['abc']
you can save the dict, using json module, to a file, for easy retrieval.

Find a way to add a string to a tuple

y="Peter Email: peter#rp.com Phone: 91291212"
z="Alan Email: alan#rp.com Phone: 98884444"
w="John Email: john#rp.com Phone: 93335555"
add_book=str(y) ,"" + str(z) ,"" + str(w)
**I am trying to add a contact into my address book but I am not sure how to add the string "details" into the add_book. I also found that I cannot use append because its a tuple.
details = raw_input("Enter name in the following format: name Email: Phone:")
print "New contact added"
print details
if details in add_book:
o=add_book+details
print "contact found"
print details
print add_book
address_book = {}
address_book['Alan'] = ['alan#rp.com, 91234567']#this is what I was supposed to do:
#but when I print it out, the output I get is:
{'Alan': ['alan#rp.com, 91234567']} #but I want to remove the '' and {}
I am still an amateur in programming with python so I really need all the help I can get, thanks:)!!
A simple fix would be to use a list instead of a tuple. You can do this by changing your initialization of add_book from:
add_book=str(y) ,"" + str(z) ,"" + str(w)
to:
add_book = [y,z,w]
#No need to call str() every time because your data are already strings
However, wouldn't it make more sense to organize your data as a list of dictionaries? For example:
contacts = ["Peter", "Alan", "John"]
addr_book = [len(contacts)]
for i in range(len(contacts)):
contact = contacts[i]
email= raw_input(contact+"'s email: ")
phone= raw_input(contact+"'s phone: ")
addr_book[i] = {'name':contact, 'email':email, 'phone':phone}
FURTHERMORE:
If I understood your question correctly, you have specific requirements as to how the output of your program should look. If you use the above data format, you can create whatever output you like. for example, this code
def printContact(contact):
print contact['name']+': ['+contact[email]+','+contact[phone]+']'
will output something like:
Alan: [alan#email.com,555-555-5555]
Of course you can change it however you like.
firstly [] is a list. a tuple is (,);
so what you want is
address_book['Alan'] = ('alan#rp.com', '91234567')
But this seems quite odd. What i would do is create a class
class Contact(object):
name = "Contact Name"
email = "Contact Email"
ph_number = "00000000"
def __str__(self):
return "%S: %s, %s" % (self.name, self.email, self.ph_number)
then
address_book = []
contact_alan = Contact()
contact_alan.name = "Alan"
contact_alan.email = "alan#rp.com"
contact_alan.ph_number = "91234567"
print contact
(not next to a machine with python so it might be slightly wrong. Will test it when i can get to one.)
EDIT:- as Paul pointed out in his comment:
class Contact(object):
def __init__(self, name, email, ph_number):
self.name = name
self.email = email
self.ph_number = ph_number
contact_alan = Contact(name="Alan", email = "alan#rp.com", ph_number="91234567")

Categories

Resources