How to find a string among many strings in a line - python

I have a requirement to find the user from the log.
I have a line of code from my log file. One of the strings in the line is a userid. I have the list of all userid also.
Is there any easy way to identify the userid mentioned in the line.
Eg: Calling Business function ProcessSOMBFCommitment_Sourcing from F4211FSEditLine for ND9074524. Application Name [P421002], Version [] (BSFNLevel = 3)
Here, ND9074525 is the user id. My intention is to identify the user from the line.
Other possible userid can be AB9074158, AC9074168, AD9074123, AE9074152
I do not want to loop through all the possible userid. I thought of creating a list of all userid's and find the userid used in line by some method. Not sure if it exists.

You can use this regex to fetch the user id:
[A-Z]{2}\d{7}
And then check against valid user ids.
Regex Demonstration
Code:
import re
users = ['AB9074158', 'AC9074168', 'AD9074123', 'AE9074152']
s = 'Calling Business function ProcessSOMBFCommitment_Sourcing from F4211FSEditLine for ND9074524. Application Name [P421002], Version [] (BSFNLevel = 3)'
pat = '[A-Z]{2}\d{7}'
user_id = re.search(pat, s).group(0)
print(user_id)
if user_id in users:
print("User accepted!")
else:
print("User not accepted")
Output:
'ND9074524'
'User not accepted'

Use a regex to find all strings that match the pattern of a userid; then you can see if any of them are actual userids.

Related

Insert a value before comma in a file

I'm new to Python and I'm trying to create a simple program for login which reads/writes the information to/from a text file, but I'm having an issue.
Let's say I have the following content in a text file:
mytest#gmail.com, testPass123
First the email and after the comma the password. How can I read those two separately?
I have used .split(',') but it stores the whole line.
If I run this:
email = []
for line in file:
email.append(line.split(','))
print(email[0])
I get the following output:
['mytest#gmail.com', ' testPass123\n']
I think your variable naming is confusing you here. If you name email accounts, things might become clearer:
accounts = []
for line in file:
accounts.append(line.strip().split(','))
for email, password in accounts:
print("Email:", email, "Password:", password)
You may be looking for multiple assignment
>>> a, b = "em#ail, pass".split(",")
>>> a
'em#ail'
>>> b
' pass'

Stacked in a loop creating friendship with tweepy

So Im trying to follow users, but the problem is that it works on every user except the last one that I have in my to_follow.txt:
Chile_Temblores
Aguas_Antof
costaneranorte_
onemichile
Edelaysen
Chilquinta600
CGE_Clientes
Frontel_
EnelClientesCL
javi1597
The code that Im using is the following:
def createFriends(api):
accounts = open("to_follow.txt", "r")
friends = api.friends_ids()
print("friends:", friends)
follow = accounts().split('\n')
print (follow)
for account in follow:
if account not in follow:
api.destroy_friendship(account)
for account in follow:
if account not in friends:
print("account: ", account)
fuentes.append(account)
api.create_friendship(account)
print("friendship created")
print(fuentes)
accounts.close()
So when I print what is happening, it stops in javi1597 and it does not exit de execution, Where is the problem?
I think you should have used the variable "accounts" instead of using the file name "to_follow" as a method:
def createFriends(api):
accounts = open("to_follow.txt", "r")
friends = api.friends_ids()
print("friends:", friends)
print(accounts)
for account in accounts:
if account not in friends:
print("account: ", account)
fuentes.append(account)
api.create_friendship(account)
print("friendship created")
print(fuentes)
accounts.close()
Else I don't understand where the function to_follow() is coming from and why you don't use the created variable "accounts".
Edit: I refactored your code. You don't have to split the file but can directly iterate over the rows with "for in".
Edit 2: When you trying to add the last element "javi1597" it could be possible, that it also contains the "end of file" and it should be removed before you pass it into your API. Only an idea.

modify url address in python

I'm trying to add strings into a URL address in order to get data from a server.
the string depends on a user input. the user input i saved under a variable called id.
id = str(raw_input("Enter a valid ID: "))
my url address looks like this:
url = "http://www.test.com/?%s&%s" % (id, api_key)
when i'm printing the URL just to check I've got everything in order i get this result:
http://www.test.com/?<built-in function id>&ef50250
I followed some other questions and some other tutorials but none seem to clearly it for my.
It is my first project so excuse if i ask any obvious questions.
id is a built-in function. Give a different name to your variable. By the way, raw_input returns str. So you can get rid of str(raw_input(...))
>>> my_id = raw_input("Enter a valid ID: ")
Enter a valid ID: 12
>>> api_key='abc'
>>> url = "http://www.test.com/?%s&%s" % (my_id, api_key)
>>> print url
http://www.test.com/?12&abc

Check variable against specific line in a text file | Python 3.6.x

Pretend I am making an email script. The user has already made a username and password, which has been stored in a text file so they can log in later at anytime.
The user needs to be able to log in. I want python to check that the users input matches the information in the text file from earlier, on their corresponding line. Capitalization doesn't matter.
The text file that was created initially reads:
johncitizen
johnspassword
My python script should read something like:
##Reads text file
guessusername = input('What is your username? ')
guesspassword = input('What is your password? ')
if guessusername.lower() = lines[0] and guesspassword = lines[1]:
##Grant access
I don't mind if capitalization is wrong, as long as the string itself matches up
Before first of all, what you are doing with plain text password storage is ill-advised. You should be using hashing+salting, or even better, pick a decent framework to work in and learn from how they do it.
First of all, your data storage format should be more record like:
user_id<tab>username<tab>password
user_id<tab>username<tab>password
user_id<tab>username<tab>password
In that case, you are able to read the file like this:
username = ... #user input
password = ... #user input
found_user_id = None
with open('pass.txt', 'rt') as f:
for line in f:
fields = line.split("\t")
if fields[1] == username and fields[2] == password:
found_user_id = fields[0]
break
#okay, here if found_user_id is not None, then you have found them
#if it is None, then you did not find them.
Truly, a database is much more useful than a text file, but this is how it works!

Python- Reading back usernames and passwords into a program to authenticate

I am currently writing a program in Python that asks if you have a log in. If no, they proceed to create a username and password. If yes, they log in and their details are checked against a text file. The text file looks like this (Username then password):
whitehallj27
EXpass%20
Username2
EXPASSWORD%%%
james_27
password1234
I am trying to figure out a way of programming this as simply as possible. It seems to work, but isn't nearly as simple and doesn't really work how I thought it would. Here is the code snippet:
logins={}
usernames_passwords=open("UsernamesAndPasswords.txt","r")
count=0
for line in usernames_passwords:
count=count+1
count=count/2
usernames_passwords.close()
usernames_passwords=open("UsernamesAndPasswords.txt","r")
try:
for x in range(count):
username=usernames_passwords.readline()
password=usernames_passwords.readline()
logins[username]=password
except TypeError:
count=int(count+0.5)
for x in range(count):
username=usernames_passwords.readline()
password=usernames_passwords.readline()
logins[username]=password
usernames_passwords.close()
print(logins)
Also, how would I go about authenticating the username and password to check it's correct.
Many thanks,
James Duxbury
Assuming that variables user and passwd have the username and password provided by the user, then just read the file in two lines:
file_contents = []
with open("UsernamesAndPasswords.txt","r") as f: #use "with", it will auotamtically close the file
file_contents = f.readlines()
usernames = file_contents[0::2] #step by 2, take all elements starting at index 0
passwords = file_contents[1::2] #step by 2, take all elements starting at index 1
found_at_index = -1
for i in range(0,len(usernames)):
if user == usernames[i] and passwd == passwrods[i]:
found_at_index = i
break
if found_at_index >= 0 :
#do whatever you want, there is match
else:
#I don't know what you wanted to do in this case
Please read this for the with keyword and this for how to read a file nicelly.
Also this about the [::] syntax.
You could create a dictionary with the user names and passwords like this:
dict = {
'user-name': 'password-hashing',
'another-user': 'another-password'
}
after you've done it you can save this dict in a json file, and load its content when the user asks for login.
the docs for handling json files with python: https://docs.python.org/3/library/json.html
obs.: it will look simpler, but its not the best way of doing this king of thing

Categories