I'm Trying to create phone book program using python3. If name/phone number given already exist in phone book i need to inform the user to give unique name/number. Below is my code
import re,os
take_input='yes'
def duplicate_exists(arg):
if os.path.exists('ph_dir.txt'):
with open('ph_dir.txt','r') as rp:
contents=rp.read()
res=re.findall(arg,contents)
if res:
print(f"{arg} already exist.")
tk_ip='yes'
else:
tk_ip='no'
return tk_ip
while take_input == 'yes':
name=input("Enter the name:")
phno=input("Enter phone number:")
name=name.strip()
phno=phno.strip()
take_input=duplicate_exists(name)
take_input=duplicate_exists(phno)
with open('ph_dir.txt','a') as wp:
contents=wp.write(f'\n{name}:{phno}')
In the above code i'm using duplicate_exists() to find the duplicate for both name and phno
ph_dir.txt already has below entry
abcd:12345
now if i give the input as abc and 123 it says already exists.
Improper op:
Enter the name:abc
Enter phone number:123
abc already exist.
123 already exist.
Enter the name:
I tried word boundary res=re.findall(\barg\b,contents) in regex. But this will give syntax error SyntaxError: unexpected character after line continuation character. I'm using same function to find duplicate of phone number also. So i cant hard code any value here. How to solve this problem?
use this regex: re.findall(f'{arg}:.*|.*:{arg}', name)
def duplicate_exists(arg):
if os.path.exists('ph_dir.txt'):
with open('ph_dir.txt','r') as rp:
contents=rp.read()
res=re.findall(f'{arg}:.*|.*:{arg}', contents)
if res:
print(f"{arg} already exist.")
tk_ip='yes'
else:
tk_ip='no'
return tk_ip
also you can check both name and phno in one regex matching:
def duplicate_exists(name, phno):
if os.path.exists('ph_dir.txt'):
with open('ph_dir.txt','r') as rp:
contents=rp.read()
res=re.findall(f'{name}:.*|.*:{phno}', contents)
if res:
print(f"{name} or {phno} already exist.")
tk_ip='yes'
else:
tk_ip='no'
return tk_ip
Related
I want to code and creat a bot for telegram that does these things:
1 - shows a massage to the person that hit start button
2 - then it gets a name as an input
3 - then again shows a massage
4 - getting an input
5 - at the end add the inputs to a defualt text and showing it;
for exampele:
-start
+Hi What is your name?
-X
+How old are you?
-Y
+Your name is X and you are Y years old.
My second Question is that how can I Connect to bots together, for example imagine I want to pass some input from this bot to make a poll(voting massage), in order to do that I should send the name to let's say #vote, how is that possible and what should I learn to do such things with my bot?
First you're gonna have to explore telegram bot API documentation here.
Then you should choose your programming language and the library you want to use.
There are different libraries for each language, I'm gonna name a few:
Go: https://github.com/aliforever/go-telegram-bot-api (DISCLAIMER: I wrote and maintain it)
Python: https://github.com/eternnoir/pyTelegramBotAPI
NodeJS: https://github.com/telegraf/telegraf
I'm gonna give you an example for what you want in python using pyTelegramBotAPI:
First install the library using pip:
pip install git+https://github.com/eternnoir/pyTelegramBotAPI.git
Then run this script:
import telebot
API_TOKEN = 'PLACE_BOT_TOKEN_HERE'
bot = telebot.TeleBot(API_TOKEN)
user_info = {}
def set_user_state(user_id, state):
if user_id not in user_info:
user_info[user_id] = {}
user_info[user_id]["state"] = state
def get_user_state(user_id):
if user_id in user_info:
if "state" in user_info[user_id]:
return user_info[user_id]["state"]
return "Welcome"
def set_user_info(user_id, name=None, age=None):
if name is None and age is None:
return
if name is not None:
user_info[user_id]["name"] = name
if age is not None:
user_info[user_id]["age"] = age
def get_user_info(user_id):
return user_info[user_id]
#bot.message_handler()
def echo_all(message):
user_id = message.from_user.id
if message.text == "/start":
bot.reply_to(message, "Hi What is your name?")
set_user_state(user_id, "EnterName")
return
user_state = get_user_state(user_id)
if user_state == "EnterName":
set_user_info(user_id, name=message.text)
bot.reply_to(message, "How old are you?")
set_user_state(user_id, "EnterAge")
return
if user_state == "EnterAge":
set_user_info(user_id, age=message.text)
info = get_user_info(user_id)
bot.reply_to(message, "Your name is %s and you are %s years old." %(info["name"], info["age"]))
set_user_state(user_id, "Welcome")
return
bot.reply_to(message, "To restart please send /start")
bot.infinity_polling()
Here we use a dictionary to place user state and info, you can place them anywhere like databases or json files.
Then we update a user's state based on their interactions with the bot.
For your second question, bots cannot communicate with each other so you should look for other solutions. In the case of your question where you want to create a poll, you should check sendPoll method as well as PollAnswer object which you receive when a user votes in a poll.
I have a search request written as
import sqlite3
conn = sqlite3.connect('locker_data.db')
c = conn.cursor()
def search1(teacher):
test = 'SELECT Name FROM locker_data WHERE Name or Email LIKE "%{0}%"'.format(teacher)
data1 = c.execute(test)
return data1
def display1(data1):
Display1 = []
for Name in data1:
temp1 = str(Name[0])
Display1.append("Name: {0}".format(temp1))
return Display1
def locker_searcher(teacher):
data = display1(search1(teacher))
return data
This allows me to search for the row containing "Mr FishyPower (Mr Swag)" or "Mr FishyPower / Mr Swag" with a search input of "FishyPower". However, when I try searching with an input of "Swag", I am then unable to find the same row.
In the search below, it should have given me the same search results.
The database is just a simple 1x1 sqlite3 database containing 'FishyPower / Mr Swag'
Search Error on 'Swag'
Edit: I technically did solve it by limiting the columns being searched to only 'Name' but I intended the code search both the 'Name' and 'Email' columns and output the results as long as the search in within either or both columns.
Edit2: SELECT Name FROM locker_data WHERE Email LIKE "%{0}%" or Name LIKE "%{0}%" was the right way to go.
I'm gonna guess that Mr. FishyPower's email address is something like mrFishyPower#something.com. The query is only comparing Email to teacher. If it was
WHERE Name LIKE "%{0}%"
OR Email LIKE "%{0}%"'
you would (probably) get the result you want.
I'm using Python 3.6.3.
I am trying to validate a username and password from a csv file. The usernames and subsequent passwords are on new lines in the text file, so when appended to an empty array I called "up" it was turned into a 2d array with each line a list within "up". I ask the user for a username and a password. So then I tried to use a for loop (for x in up) to loop over each list in up via up[up.index(x)], and then used .index(username) straight afterwards in a variable called j (j = up[up.index(x)].index(username)). The code will be given, with the section I'm having trouble with highlighted.
These are the contents of the csv file: Text File
When I run the code the it returns an error that says the username in not in the list. I've searched for answers but couldn't find anything. Is there something that I've overlooked?
Any help will be gratefully appreciated.
import csv
validoption = ["i","u"]
while True:
option = input("Sign in or sign up\nPlease enter 'i' to sign in or 'u' to sign up: ")
if option in validoption:
if option is "i":
with open("login.txt","r") as l:
up = []
read = csv.reader(l)
count = 0
for line in read:
up.append(line)
count=+1
invalid = True
while invalid:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
if [[y is username for y in x] for x in up]:
for x in up:
j = up[up.index(x)].index(username)
if password in up[up.index(x)][j+1]:
invalid = False
else:
print("Password is incorrect")
else:
print("Username is not recognised")
else:
with open("login.txt","a") as l:
username = input("Please enter your username: ")
while True:
password = input("Please enter your password\nPlease make sure that your password is longer than 8 characters, has a capiatal letter and a number: ")
if len(password)<8:
if any(p.isupper() for p in password):
if any(p.isdigit() for p in password):
break
else:
print("Password must have one number in it\n")
else:
print("Password must have one capital letter\n")
else:
print("Password must have more than 8 charaters")
userdetails = username+","+password
l.write(userdetails)
l.write("\n")
Thank you :)
y is username tests if the two values are the same object, not equivalent objects. Use == instead.
Additionally, you should consider using the username as the key of a dict, then you can use in and eliminate some of the loops in your application code.
i want to allow only alphanumeric password i have written following code to match the same
but the same is not working
Regex.IsMatch(txtpassword.Text, "^[a-zA-Z0-9_]*$") never return false
even if i type password test(which do not contain any number).
ElseIf Regex.IsMatch(txtpassword.Text, "^[a-zA-Z0-9_]*$") = False Then
div_msg.Attributes.Add("class", "err-msg")
lblmsg.Text = "password is incorrect"
I have tried this also
Dim r As New Regex("^[a-zA-Z0-9]+$")
Dim bool As Boolean
bool = r.IsMatch(txtpassword.Text) and for txtpassword.Text = '4444' , bool is coming true i dont know what is wrong.
First of all, the '_' is not a valid alpha-numeric character.
See http://en.wikipedia.org/wiki/Alphanumeric
And, second, take another look at your regular expression.
[a-zA-Z0-9_]*
This can match 0 OR more alpha-numeric characters or 0 OR more '_' characters.
Using this pattern, a password '&#&#^$' would return TRUE.
You probably want to test for 1 OR more characters that ARE NOT an alpha-numeric. If that test returns TRUE, then throw the error.
Hope this helps.
Try the following Expression:
([^a-zA-Z0-9]+)
This will match if your Password contains any character that is not alphanumeric.
If you get a match, do your error handling.
So based on the Regex that you have in the question, it appears you want a password with one lower-case and upper-case letter, one number, and an _; so here is a Regex that will do that:
(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*_).{4,8}
Debuggex Demo
The {4,8} indicates the length of the password; you can set that accordingly.
Okay, so I already have a Pipe where I extracted the string I need from item.description, using the Loop and String Regex modules, and am emitting the results with the "emit results" option. Now, where do I go from here?
EDIT: Since an example was requested, here is one:
The item.title is "NBA Game: Lakers vs. Clippers" and the item.description is "The game went into overtime. The final score was 110-90." So the I'd like to extract "110-90" and copy it to the title, where it would then be "... Clippers (110-90)".
1/ Put the score in "scorefield"
Rename operator: [item.description] [COPY AS] [scorefield]
Regex operator : in [scorefield] replace [.*\(([^)]+)\).*] with [$1]
2/ Append score to item.title
Regex operator : in [item.title] replace [($)] with [$1 ${scorefield}]
Nota :
In the above lines the outside square brackets are to be omitted unless noted otherwise
For complements :
http://beckism.com/2009/04/yahoo_pipes/
https://brooksbayne.wordpress.com/2009/01/11/using-regular-expressions-with-yahoo-pipes/