Search a String in text file in python - python

import os
import random
import sys
def search(a):
datafile = open("test.txt","r")
quote = datafile.read()
quote_list = quote.split(" ")
d = len(quote_list)
print(quote_list)
for x in range(0,4):
string = quote_list.pop()
print(string)
if(string==a):
return 0
else:
continue
print("Enter the word to search")
b = sys.stdin.readline()
c=search(b)
if(c==0):
print("Found")
else:
print("Not Found")
This code for searching a particular string in a text file is not working. Please help me to rectify the issue.

Try changing the line:
c=search(b)
to:
c=search(b.strip())
The newline in the user-input is probably what's getting in your way.
Other than that you probably want to change:
for x in range(0,4):
to:
for x in quote_list:
and get rid of the parameter d

Related

Trying to find URL's in a file and save to a dictionary?

For my coding assignment I am to find all URL's in a mem.raw file and then save the URL's and how many of each was found in a prettytable and output it. The code that seems to be the issue if the "for URL in fileContents" but I can't figure out why. It's iterating over this for loop but isn't finding the matches and saving it to the dictionary. Any ideas why?
Here is the code I have
import re
import os
import sys
from prettytable import PrettyTable
largeFile = input("Enter the name of a large File: ")
chunkSize = int(input("What size chunks? "))
urlPattern = re.compile(b'\w+:\/\/[\w#][\w.:#]+\/?[\w\.?=%&=\-#/$,]*')
matches = {}
try:
if os.path.isfile(largeFile):
with open(largeFile, 'rb') as targetFile:
fileContents = targetFile.read(chunkSize)
print("\nURLs")
for URL in fileContents:
try:
urlMatches = urlPattern.findall(fileContents)
cnt = matches[URL]
cnt += 1
matches[URL] = cnt
except:
matches[URL] = 1
tbl = PrettyTable(["Words", "Occurrences"])
for word, cnt in matches.items():
tbl.add_row([word, cnt])
tbl.align = '1'
print(tbl.get_string(sortby="Occurrences", reversesort=True))
break
else:
print(largeFile, " is not a valid file")
sys.exit("Script Aborted")
except Exception as err:
print(err)
The code does not make sense. Not even sure why the while loop is there.
for eachURL in urlMatches:
while True:
matches = matches[eachURL]
You'll need to do something like
for URL in urlMatches:
if URL not in matches:
matches[URL] = 1
else:
matches[URL] += 1
Now that you have edited the question, new issues arise.
The following should work:
fileContents = targetFile.read(chunkSize)
urlMatches = urlPattern.findall(fileContents)
for URL in urlMatches:
if URL not in matches:
matches[URL] = 1
else:
matches[URL] += 1
Note that you'll need an outer loop to cover the file contents after chunk size.

Getting python to stop printing lines from a file at a certain time using Re

Basically what I am trying to do is to get it to print the lines of a file that have a timestamp in a specific range that is input from the user.
import sys, re
f = open('log.txt', encoding='ISO-8859-1')
h = open('errorsfound.txt', "w")
print("What time do you want to begin searching the logs?")
starttimestamp = input()
starttimestamp = str(starttimestamp)
print("What time do you want to stop searching the logs?")
endtimestamp = input()
endtimestamp = str(endtimestamp)
use = False
lines = f.readlines()
for line in lines:
if re.search(starttimestamp, line): use = True
if re.search(endtimestamp, line): use = False
if use:
if "error" in line:
h.write (line)
if use:
if "Failed" in line:
h.write (line)
if use:
if "ERROR" in line:
h.write (line)
if use:
if "WARN" in line:
h.write (line)
if use:
if "Requeue:" in line:
h.write (line)
f.close()
h.close()
I have it to where it prints starting from a certain time, but I'm having trouble getting it to stop printing after a certain time. The timestamps are in format 04:00:48. So when it prompts I input say 04:00:48 as the start time and 04:15:48 as the end time. I am a fairly new coder so I apologize if I have left anything out. Thank you for looking!
As a new coder you are missing some format but good job anyways!
For time you should get used to use modules like datetime, using str() on input is redundant since it saves the result of the input as str already, and least but not last re is for regular expressions, there are other ways of parsing text ( if my_text in line: then x) but re is a good tool anyways.
import sys, re
import datetime
f = open('log.txt', encoding='ISO-8859-1')
h = open('errorsfound.txt', "w")
print("What time do you want to begin searching the logs?")
starttimestamp = str(input()) # redundant use of str()
print("What time do you want to stop searching the logs?")
endtimestamp = str(input()) # redundant use of str()
# use = False # bad name for a variable, use more descripting ones
write_time_flag = False
lines = f.readlines()
"""
my_solution
"""
try:
start_time_stamp = datetime.datetime.strptime(input, "%H:%M:%S")
break
except:
print("Use Format Hours:Minutes:seoconds (HH:MM:SS)")
try:
end_time_stamp = datetime.datetime.strptime(input, "%H:%M:%S")
break
except:
print("Use Format Hours:Minutes:seoconds (HH:MM:SS)")
for line in lines:
# I don't know the format of your log file so, read the hours with datetime
# and check condition
if readtime > start_time_stamp and readtime < end_time_stamp:
use = True
else:
use = False
if use:
if "error" in line:
h.write (line)
elif "Failed" in line:
h.write (line)
elif "ERROR" in line:
h.write (line)
elif "WARN" in line:
h.write (line)
elif "Requeue:" in line:
h.write (line)
f.close()
h.close()

Open files and store contents in variable

Code:
import secrets
import sys
import time
import string
from tenacity import (retry , stop_after_attempt)
#Required Defs
var = open('conf.txt','r+')
content = var.read()
print(content)
def get_random_string(length):
letters = string.ascii_lowercase
num = string.ascii_uppercase
punc = string.punctuation
spec = string.hexdigits
one = str(num) + str(punc) + str(spec)
result_str = ''.join(secrets.choice(one) for i in range(length))
print("Random string of length", length, "is:", result_str)
#Closing All Defs Here
#retry(stop=stop_after_attempt(5))
def start():
pasw = input("Do YOu Want A Random Password: y/n: ")
if pasw == 'y':
leng = input("Please Type The Length Of The Password You Want: ")
try:
len1 = int(leng)
get_random_string(len1)
time.sleep(4)
except ValueError:
print("Only Numbers Accepted")
time.sleep(4)
elif pasw == 'n':
sys.exit("You Don't Want TO Run The Program")
time.sleep(3)
else:
raise Exception("Choose Only From 'y' or 'n'")
start()
Problem:
I want to read contents of file called conf.txt and want to include
only 2 chars 3 letters and it is based on conf.txt. How can I achieve
this? Please tell conf.txt contains:
minspec = 1 #This tells take 2 special chars chars
minnumbers = 3 #This tells take 3 Numbers
minletter = 2 #This tells take 2 lower chars
minhex = 2 #This tells take 2 hex numbers
with open('file.txt', 'r') as data:
contents = data.read()
In the above example we are opening file.txt in read mode with the object name data.
We can use data.read() to read the file and store it in the variable name contents.
One of the advantage of using with is that we don't need to close the file, it automatically closes file for you.
For reading only selected bytes for a file object can be used:
the seek method (to change the file object’s position);
the read method has the optional param - number of bytes to read.
Example:
f = open('workfile', 'rb') # b'0123456789'
f.read(2) # reading only the first two bytes(b'01')
f.seek(6) # go to the 6th byte in the file
f.read(3) # reading 3 bytes after 6 position(b'678')

Append and replace objects in one string

I'm writing a text encoder/crypter (all by myself) and i can't understand how to append and replace characters in the string :-/
The code:
import os, sys, random
dig = 0
text_encoded = ""
text = ""
try:
if os.path.isfile(sys.argv[1]) == True:
with open(sys.argv[1], "r") as text:
text = text.readlines()
except:
pass
if text == "":
print("Write the text to encode")
text = input()
text = text.split()
for _ in range(len(text)):
text_encoded = text[dig].replace("qwertyuiopasdfghjklzxcvbnm ", "mnbvcxzlkjhgfdsapoiuytrewq#")
dig = dig+1
print("Your encoded text is:\n"+text_encoded)
Here is some output:
Write the text to encode
lo lolo lol lol
Your encoded text is:
lol
If you can help me in any way, thank you :-)
If I'm getting you correctly, you want to replace q with m, w with n and so on. Try the following
import os, sys, random
dig = 0
text_encoded = ""
text = ""
try:
if os.path.isfile(sys.argv[1]) == True:
with open(sys.argv[1], "r") as text:
text = text.readlines()
except:
pass
if text == "":
print("Write the text to encode")
text = input()
mychars=list("qwertyuiopasdfghjklzxcvbnm ")
myencode=list("mnbvcxzlkjhgfdsapoiuytrewq#")
charmap=zip(mychars,myencode)
_map = dict(charmap)
encoded_text = ''.join(_map.get(c) for c in text)
print("Your encoded text is:\n"+encoded_text)
The strings in your question mention that you want to replace ' ' with #. If you do not want to do that, just remove the last characters from both of the above strings.
have two lists instead of strings like from_ = "abc".split() and to_ = "def".split()
look for your char in from_ and get the index, get the same index char from to_ and stitch it to a new sentence.
example:
from_ = "abc".split()
to_ = "def".split()
old_msg = "ab ab"
new_msg = ""
for each in old_msg.split():
new_msg = new_msg + to_[from_.index(each)]
Hope this helps, please add missing char handling and any other edge cases
Or you can use str.translate
import os, sys, random
from pathlib import Path
TEXT_MAP = ("qwertyuiopasdfghjklzxcvbnm ", "mnbvcxzlkjhgfdsapoiuytrewq#")
def main():
text = ''
if len(sys.argv) > 1:
fname = sys.argv[1]
p = Path(fname)
if p.is_file():
text = p.read_text().strip()
print(f'Text from {p} is: {text}')
if not text:
text = input("Write the text to encode: ").strip()
trantab = str.maketrans(*TEXT_MAP)
text_encoded = text.translate(trantab)
print("Your encoded text is:\n"+text_encoded)
if __name__ == '__main__':
main()

Python - searching if string is in file

I want to search for string in file and if there is string make action and if there isn´t string make other action, but from this code:
itcontains = self.textCtrl2.GetValue()
self.textCtrl.AppendText("\nTY: " + itcontains)
self.textCtrl2.Clear()
pztxtflpath = "TCM/Zoznam.txt"
linenr = 0
with open(pztxtflpath) as f:
found = False
for line in f:
if re.search("\b{0}\b".format(itcontains),line):
hisanswpath = "TCM/" + itcontains + ".txt"
hisansfl = codecs.open(hisanswpath, "r")
textline = hisansfl.readline()
linenr = 0
ans = ""
while textline <> "":
linenr += 1
textline = hisansfl.readline()
hisansfl.close()
rnd = random.randint(1, linenr) - 1
hisansfl = codecs.open(pztxtflpath, "r")
textline = hisansfl.readline()
linenr = 0
pzd = ""
while linenr <> rnd:
textline = hisansfl.readline()
linenr += 1
ans = textline
hisansfl.close()
self.textCtrl.AppendText("\nTexter: " + ans)
if not found:
self.textCtrl.AppendText("\nTexter: " + itcontains)
wrtnw = codecs.open(pztxtflpath, "a")
wrtnw.write("\n" + itcontains)
wrtnw.close
If there is not that string it is working corectly, but if there is that string, what i am searching for it makes if not found action. I really don´t know how to fix it, i have already try some codes from other sites, but in my code it doesn´t works. Can somebody help please?
Are you saying that the code underneath the following if statement executes if the string contains what you're looking for?
if re.search("\b{0}\b".format(itcontains),line):
If so, then you just need to add the following to the code block underneath this statement:
found = True
This will keep your if not found clause from running. If the string you are looking for should only be found once, I would also add a break statement to your first statement to break out of the loop.

Categories