I've been trying to create a program that takes an input and checks to see whether that input is in some text from a file. My end goal is to create a user login GUI, but I will not show the code for the GUI here as there is quite a lot.
I need to work out how to compare text from an input and from the file.
This is my code so far
def check(entry):
search = open('password.txt', 'r')
if str(entry) in str(search):
return (entry, "Word found")
else:
return entry, ("Word not found")
with open('password.txt', 'r') as text:
print (text.read())
while True:
entry=input("\nSearch for word: ")
print(check(entry))
When I run the code it will say that 1, 2, 5 and 12 are all in the text but none of the words that are in text are confirmed.
If anyone could help it would be appreciated, thanks.
Ignoring the security bad ideas covered in another comment, str(search) doesn't work like you think it does. If you print it, you should see something like:
<open file 'password.txt', mode 'r' at 0x0000000001EB2810>
which is a description of the object you created with the open function. You need to read the file into a string first with the .read() method.
Related
UPDATE
So I added strip() to list1. I am including the updated results.
updated output file
location?bobThings things thingyes, bob, thing, sara, more, location, ?
Yes, this is all returned on the one line.
It did miss the yes in the search, and now it is all one line smashed together.
How do I get it so that it returns with the spaces like before and on a new line for each positive result?
So, I'm new to python and still learning. I am writing a program that would allow a user to input keywords and search a input file for these keywords, then save the results to an output file.
So far, I can get it to do the search, but it is only returning certain lines from positive hits instead of all the lines. I originally thought this was because the of the new line attached to each item in the file, but I managed to strip that away and it is still not providing the correct information in the output file.
So the input file says:
Temp Chat Log
age
sex
location
?
sex
age
phone number
words
bob
Things things thing
09/03/2018
The keyword search is (user input):
yes, bob, thing, sara, more, location, ?
The output file is only getting this return:
Things things thing
I have tried removing the '\n', I have tried saving to a new file just in case there was something wrong with the original one I'm overwriting, I have tried re.search and re.replace, I've tried making a function but this is the closest I've gotten to getting the program to do this piece. The problem, I think, is with the last section of code, but I'm providing code for all pieces used in that last section. In the final section there are extra print lines because I was trying to see what was happening with the code as it progressed through this section of the program.
# Ask user for the path to the text file they would like to use
print ("Please provide a valid path to the chat log text (.txt) file. Example: C:\ Users \ USERNAME \ Documents")
# Save the path from the user input
path1 = input ()
# Checking the user input for the .txt file extension
if os.path.splitext(path1)[1] != ".txt":
print (path1 + " is an unknown file format. Please provide a .txt file.")
path1 = input()
else:
print ("Thank you for providing a text file.")
# Using a while loop to ensure this is a valid path
while not os.path.isfile(path1):
print ("Please provide a valid path to the chat log text (.txt) file.")
path1 = input ()
print ("File was successfully retrieved.")
# Ask user for needed keywords or symbols
user_keywords = input("What keywords or special symbols would you like to search the provided file for?\n"
"Please separate each entry with a comma.\nIf you would like to just search for question marks,"
" please just type n.\n")
# Holding list, using comma as a way to separate the given words and symbols
list1 = [s.strip().lower() for s in user_keywords.split(',')]
# Print list for user to see
print("You have entered the following keywords and/or special symbols: ", list1)
# Opens a new file for saving the results to.
print("Please list the path you would like the new file to save to. Example: C:\ Users \ NAME \Desktop\File name.")
outFileName = input()
# Opens the file under review.
with open(path1,'r') as f, open(outFileName, 'w') as w:
f = f.readlines()
f[:] = [f.rstrip('\n') for f in f]
for line in f:
if any(s in line.lower() for s in list1):
print(f)
print(list1)
print(line)
w.write(line)
w.close()
No error messages.
Expected Output See above update
New file at given output file path, with the positive result lines listed. So in this case, the file should have these lines on it.
bob
Things things thing
location
?
Current Output See above update
The only positive return that is happening is:
Things thing thing
I am a newbie I am trying to implement a code where if I type text it will look inside the file and will say if there's something matched or not if doesn't matched anything it will display no record however this below code is not giving the right output any idea thank you very much in advance
input = raw_input("Input Text you want to search: ")
with open('try.txt') as f:
found = False
if input in f:
print "true"
found = True
if not found:
print('no record!')
In order to match a string against the text from the file, you need to read the file:
with open('try.txt') as f:
data = f.read()
Then to check if a string is found in the file, check like this:
if input_ in data:
pass
Also, two tips:
1) Indent your code correctly. Use four spaces for every level of indentation.
2) Don't use reserved keywords to name your variables. Instead of input, use input_ or something else.
You are not actually reading the file, try something like file_content = f.read() and then do a if input in file_content.
This should print "true" if found or "no record!" for not found
I've not included your boolean "found" variable because it's not used.
First the file data is read into "data" variable as a string then we perform a check with in operator
input = raw_input("Input Text you want to search: ")
with open('try.txt', 'r') as myfile:
data=myfile.read()
if input in data:
print "true"
else:
print('no record!')
Hey i have quite a simple problem which i haven't been able to find anywhere. Basically i need to know how to make the user input a problem and then keywords from that input will be identified. Now these keywords will be stored in a couple text files and the relevant text file must be opened e.g. key word water opens the water text file and then a series of yes or no questions presented to the user after which will eventually result in two outcomes.
I really have looked everywhere on how to do this and all code looks different or isn't what i'm looking for. Any help on any aspects of the code would be greatly appreciated.
#Task 2 Trouble-Shooter 1.0
#Zacharriah River Howells
file = open('problem1','r')
import time
print('Hello and welcome to the mobile phone Trouble-Shooter!')
time.sleep(2)
print('Please input what is wrong with your phone')
print file.read()
This is what i have so far and it works up until the last line.
Try this:
import time
print('Hello and welcome to the mobile phone Trouble-Shooter!')
time.sleep(2)
need = raw_input('Please input what is wrong with your phone ')
file = open(need,'r')
print file.read()
The raw_input function is built into Python 2 and it returns a string. Next you open the file with the name that was inputted and print out its contents.
I am trying to make a small text creator application using Python. The concept is just the same as ordinary text creator (e.g. notepad). But I got difficulties to allow users to type a lot of paragraphs. So far, I am just able to allow users to type 2 paragraphs. Is there anyone can help me? Here is my script:
print "Welcome to 'Python Flat Text Creator'."
print "Please enter the name of your file and its extension (.doc atau .txt)."
filename = raw_input("> ")
target = open(filename, 'w')
typeyourtext = raw_input("Type below: \n")
target.write(typeyourtext + "\n")
typeyourtext = raw_input("\n")
target.write(typeyourtext + "\n")
target.close()
An easy answer would be to simply put the typing and displaying of the text in a while(true) block and waiting for something (key press or set of characters) to break the cycle. But I'm not sure if you want to do it this simple.
Try to go around it with inserting the characters one by one as other text editors - take a look at Vim for example. The system which is used there is fairly simple and convenient.
Edit:
Getting keypress: How to accept keypress in command line python?
Do while true cycle: http://wiki.python.org/moin/WhileLoop
at the end of each cycle if the input char isn't chr(27), which is ESC key, then append to the text which you are creating and display it.. but this isn't good for files which are large in size..
You can use a while loop set to end when the user does not input anything at all.
target = open(filename, 'w')
previousKeypress = 0
print("Type below:\n")
while previousKeypress != "":
typeyourtext = raw_input("")
target.write(typeyourtext + "\n")
previousKeypress = typeyourtext
target.close()
If you intend for users to put additional new lines in the document through no inputs, you can set the condition to react to a certain combination of characters like maybe "abc123" to end it.
You can even ask the user to set this ending combination through another raw_input at the very beginning of the program.
The Problem - Update:
I could get the script to print out but had a hard time trying to figure out a way to put the stdout into a file instead of on a screen. the below script worked on printing results to the screen. I posted the solution right after this code, scroll to the [ solution ] at the bottom.
First post:
I'm using Python 2.7.3. I am trying to extract the last words of a text file after the colon (:) and write them into another txt file. So far I am able to print the results on the screen and it works perfectly, but when I try to write the results to a new file it gives me str has no attribute write/writeline. Here it the code snippet:
# the txt file I'm trying to extract last words from and write strings into a file
#Hello:there:buddy
#How:areyou:doing
#I:amFine:thanks
#thats:good:I:guess
x = raw_input("Enter the full path + file name + file extension you wish to use: ")
def ripple(x):
with open(x) as file:
for line in file:
for word in line.split():
if ':' in word:
try:
print word.split(':')[-1]
except (IndexError):
pass
ripple(x)
The code above works perfectly when printing to the screen. However I have spent hours reading Python's documentation and can't seem to find a way to have the results written to a file. I know how to open a file and write to it with writeline, readline, etc, but it doesn't seem to work with strings.
Any suggestions on how to achieve this?
PS: I didn't add the code that caused the write error, because I figured this would be easier to look at.
End of First Post
The Solution - Update:
Managed to get python to extract and save it into another file with the code below.
The Code:
inputFile = open ('c:/folder/Thefile.txt', 'r')
outputFile = open ('c:/folder/ExtractedFile.txt', 'w')
tempStore = outputFile
for line in inputFile:
for word in line.split():
if ':' in word:
splitting = word.split(':')[-1]
tempStore.writelines(splitting +'\n')
print splitting
inputFile.close()
outputFile.close()
Update:
checkout droogans code over mine, it was more efficient.
Try this:
with open('workfile', 'w') as f:
f.write(word.split(':')[-1] + '\n')
If you really want to use the print method, you can:
from __future__ import print_function
print("hi there", file=f)
according to Correct way to write line to file in Python. You should add the __future__ import if you are using python 2, if you are using python 3 it's already there.
I think your question is good, and when you're done, you should head over to code review and get your code looked at for other things I've noticed:
# the txt file I'm trying to extract last words from and write strings into a file
#Hello:there:buddy
#How:areyou:doing
#I:amFine:thanks
#thats:good:I:guess
First off, thanks for putting example file contents at the top of your question.
x = raw_input("Enter the full path + file name + file extension you wish to use: ")
I don't think this part is neccessary. You can just create a better parameter for ripple than x. I think file_loc is a pretty standard one.
def ripple(x):
with open(x) as file:
With open, you are able to mark the operation happening to the file. I also like to name my file object according to its job. In other words, with open(file_loc, 'r') as r: reminds me that r.foo is going to be my file that is being read from.
for line in file:
for word in line.split():
if ':' in word:
First off, your for word in line.split() statement does nothing but put the "Hello:there:buddy" string into a list: ["Hello:there:buddy"]. A better idea would be to pass split an argument, which does more or less what you're trying to do here. For example, "Hello:there:buddy".split(":") would output ['Hello', 'there', 'buddy'], making your search for colons an accomplished task.
try:
print word.split(':')[-1]
except (IndexError):
pass
Another advantage is that you won't need to check for an IndexError, since you'll have, at least, an empty string, which when split, comes back as an empty string. In other words, it'll write nothing for that line.
ripple(x)
For ripple(x), you would instead call ripple('/home/user/sometext.txt').
So, try looking over this, and explore code review. There's a guy named Winston who does really awesome work with Python and self-described newbies. I always pick up new tricks from that guy.
Here is my take on it, re-written out:
import os #for renaming the output file
def ripple(file_loc='/typical/location/while/developing.txt'):
outfile = "output.".join(os.path.basename(file_loc).split('.'))
with open(outfile, 'w') as w:
lines = open(file_loc, 'r').readlines() #everything is one giant list
w.write('\n'.join([line.split(':')[-1] for line in lines]))
ripple()
Try breaking this down, line by line, and changing things around. It's pretty condensed, but once you pick up comprehensions and using lists, it'll be more natural to read code this way.
You are trying to call .write() on a string object.
You either got your arguments mixed up (you'll need to call fileobject.write(yourdata), not yourdata.write(fileobject)) or you accidentally re-used the same variable for both your open destination file object and storing a string.