PYTHON: search for exact string in text document - python

I am trying to search a text file/database for an exact username but I am getting multiple outputs for my query
Here is my code:
import re
txtFile = open("test.txt", "r")
userName = raw_input("USER: ")
for line in txtFile:
if re.match(userName, line):
print line
When I enter a generic username like "dragon" I get multiple results:
>>>
USER: dragon
dragon:46.245.173.123
dragonsAreCool:3.13.136.5
How would I make the search exact instead of getting multiple results that include my query?

import re
userName = raw_input("USER: ")
with open("test.txt", "r") as txtFile:
for line in txtFile:
if re.match(userName + ':', line):
print line
break # if you sure there is only one user, add break, make you code faster, else delete it.
or:
for line in txtFile:
if line.startswith(userName + ':')
print line
break # if you sure there is only one user, add break, make you code faster, else delete it.

Related

Search text in file and print all text

okay. you didnt understand anything from the title. let me explain.
now ı have a file. There is some text in this file. for example "jack.123 jackie.321"
I want to check if the word jack exists in the file and ı wanna print "jack.123".
its my problem. ı didnt print all text.
def append(name,password):
f = open("myfile.txt", "w")
f.write("{},{}".format(name,password))
append("jack",".123")
append("jackie" , ".321")
f = open("myfile.txt" ,"r")
if "jack" in f.read():
print("query found")
Open the file and read all its contents then split on whitespace. That effectively gives you all the words in the file.
Iterate over the list of words checking to see if a word starts with the name you're searching for followed by '.'.
Note that there may be more than one occurrence so build a list.
def find_name(filename, name):
if not name[-1] == '.':
name += '.'
found = []
with open(filename) as myfile:
for word in myfile.read().split():
if word.startswith(name):
found.append(word)
return found
print(*find_name('myfile.txt', 'jack'))
def new_pass(name, passwd):
"creates file and write name and passwd to it"
with open("myfile1.txt", "a") as f:
f.write(name + "." + passwd + "\n")
new_pass("jack", "123")
new_pass("jack", "183")
new_pass("jack", "129")
new_pass("jack", "223")
def check_word(file, word):
"""checks if a word exists and returns its first occurence """
with open(file) as f:
l = f.read().split("\n")
for i in l:
if i.startswith(word):
print("query found")
return i
print(check_word("myfile1.txt", "jack"))
In python you can do it like that :
with open('file.txt', 'r') as file:
data = file.read()
if "jack" in data:
print("jack")
If I understood uncorrectly let me know

Print the title from a txt file from the given word

I have a txt file with the following info:
545524---Python foundation---Course---https://img-c.udemycdn.com/course/100x100/647442_5c1f.jpg---Outsourcing Development Work: Learn My Proven System To Hire Freelance Developers
Another line with the same format but different info and continue....
Here on line 1, Python foundation is the course title. If a user has input "foundation" how do I print out Python foundation? It's basically printing the whole title of a course based on the given word.
I can use something like:
input_text = 'foundation'
file1 = open("file.txt", "r")
readfile = file1.read()
if input_text in readfile:
#This prints only foundation keyword not the whole title
I assume that your input file has multiple lines separated by enters in this format:
<Course-id>---<Course-name>---Course---<Course-image-link>---<Desc>
input_text = 'foundation'
file1 = open('file.txt', 'r')
lines = file1.readlines()
for line in lines:
book_title_pattern = r'---([\w\d\s_\.,;:()]+)---'
match = re.search(book_title_pattern, line)
if match:
matched_title = match.groups(1)[0]
if input_text in matched_title:
print(matched_title)
Get the key value that you're searching for. User input perhaps or we'll hard-code it here for demo' purposes.
Open the file and read one line at a time. Use RE to parse the line looking for a specific pattern. Check that we've actually found a token matching the RE criterion then check if it contains the 'key' value. Print result as appropriate.
import re
key = 'foundation'
with open('input.txt') as infile:
for line in map(str.strip, infile):
if (t := re.findall('---([a-zA-Z\s]+)---', line)) and key in t[0]:
print(t[0])
You can use regex to match ---Course name--- using ---([a-zA-Z ]+)---. This will give you all the course names. Then you can check for the user_input in each course and print the course name if you find user_input in it.:
import re
user_input = 'foundation'
file1 = open("file.txt", "r")
readfile = file1.read()
course_name = re.findall('---([a-zA-Z ]+)---', readfile)
for course in course_name:
if user_input in course: #Then check for 'foundation' in course_name
print(course)
Output:
Python foundation

Removing characters in a file and also making it neat

I want to basically remove all the characters in delete list from the file (Line 11 to 15). What would be the neatest way to delete the words without making the code not neat. I am not sure whether to open the file again here which I know would not be the right way but I can't think of a different solution. Any help would be appreciated.
from os import write
import re
def readText():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt') as f:
print(f.read())
def longestWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r+') as f:
users_text = f.read()
#I want to basically remove all the char in delete list from the file. What would be the neatest way to delete the words without making the code not neat. I am not sure wether to open the file again here and re write it or what!
deleteList = ['!','£','$','%','^','&','*','()','_','+']
for line in f:
for word in deleteList:
line = line.replace(word, '')
longest = max(users_text.split(), key=len)
count_longest = str(len(longest))
print('The longest word in the file is: ' + long)
print('Thats a total of '+count_longest+' letters!')
def writeWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'w') as f:
users_text = input('Enter your desired text to continue. \n: ')
f.write(users_text)
f.close()
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r') as file:
print(file.read())
longestWord()
Had to re work it and implement it in a different def. Need to add relative paths and will be alot cleaner aswell.
from os import write
import re
def longestWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r+') as f:
users_text = f.read()
longest = max(users_text.split(), key=len)
count_longest = str(len(longest))
print('The longest word in the file is: ' + longest)
print('Thats a total of '+count_longest+' letters!')
def writeWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'w') as f:
users_text = input('Enter your desired text to continue. \n: ')
cleanText = re.sub('[^a-zA-Z0-9 \n\.]', ' ', users_text)
f.write(cleanText)
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r') as clean:
print('\nRemoved any illegal characters. Here is your text:\n\n' + cleanText + '\n')
f.close()
while True:
print("""
Welcome to Skies word text counter!
====================================================
""")
writeWord()
longestWord()
userDecide = input("""
====================================================
Would you like to enter new text and repeat?
Type 'yes' to continue else program will terminate.
====================================================
: """)
if not userDecide.lower == 'yes':
print('Application closing...')
exit()

How do i split a continuous string that is made up of two different word that are separated with "|" where i have to print just the first word?

So I am doing a task where I need to read a line from a text file which goes like this: "Name|Something" and I have to print "Username: Name" and "Password: Something". Here is what I came up with but I don't really know how to use the split command in this instance:
def main():
infile = open("users","r")
print("Username: ",e[0] for e in infile.split("|"))
print("Password: ",e[1] for e in infile.split("|"))
main()
You need to call str.split() once per input line, perhaps in a loop.
For example:
with open("users") as input_file:
for line in input_file:
username, password = line.split('|')
print("Username:", username.strip())
print("Password:", password.strip())
You have to iterate over the lines for example
with open('users', 'r') as infile:
for line in infile:
username, password = line.split('|')
print('Username: {}'.format(username))
print('Password: {}'.format(password))

Change log file with index

I have a file which contains a user:
Sep 15 04:34:31 li146-252 sshd[13326]: Failed password for invalid user ronda from 212.58.111.170 port 42579 ssh2
Trying to use index method for string to edit the user within the file. So far I am able to print the user but now to delete and put in the new user.
newuser = 'PeterB'
with open ('test.txt') as file:
for line in file.readlines():
lines = line.split()
string = ' '.join(lines)
print string.index('user')+1
Do you want to update the file contents? If so, you can update the user name, but you will need to rewrite the file, or write to a second file (for safety):
keyword = 'user'
newuser = 'PeterB'
with open('test.txt') as infile, open('updated.txt', 'w') as outfile:
for line in infile.readlines():
words = line.split()
try:
index = words.index(keyword) + 1
words[index] = newuser
outfile.write('{}\n'.format(' '.join(words)))
except (ValueError, IndexError):
outfile.write(line) # no keyword, or keyword at end of line
Note that this code assumes that each word in the output file is to be separated by a single space.
Also note that this code does not drop lines that do not contain the keyword in them (as do other solutions).
If you want to preserve the original whitespace, regular expressions are very handy, and the resulting code is comparatively simple:
import re
keyword = 'user'
newuser = 'PeterB'
pattern = re.compile(r'({}\s+)(\S+)'.format(keyword))
with open('test.txt') as infile, open('updated.txt', 'w') as outfile:
for line in infile:
outfile.write(pattern.sub(r'\1{}'.format(newuser), line))
If you want to change the names in your log, here is how.
file = open('tmp.txt', 'r')
new_file = []
for line in file.readlines(): # read the lines
line = (line.split(' '))
line[10] = 'vader' # edit the name
new_file.append(' '.join(line)) # store the changes to a variable
file = open('tmp.txt', 'w') # write the new log to file
[file.writelines(line) for line in new_file]

Categories

Resources