So let's say I have something like;
def scramble():
word = open("wordlist.txt", "a")
userword = input("Give me a word to scramble")
newword = userword.replace("a", "*")
newword2 = neword.replace("o", "0")
word.write(userword)
word.write(\n)
word.close
Take a word, replace characters with those in the code and append that to a file. How can I then create a different function where I ask the user to enter that word again, the code goes back to that file, almost "decrypts" the word and spits it back out at the user in the most simplest of terms. I don't care how messy I'm just completely lost.
I've attempted to reverse the scrambled word but every time I go to check the file for it, regardless of whether or not the word is in there it fails the check.
def unscramble():
word = open("wordlist.txt", "r")
userinput = input("Enter a word and I'll see if i have it")
userinput2 = userinput.replace("*","a")
userinput3 = userinput2.replace("0","o")
for line in word:
if userinput3 in line:
print("Yes, I do have that word. Would you like to see it scrambled?")
else:
print("Sorry, I don't have that")
Related
If i manually key the words in the txt and run the program the "word found" can be displayed but when i run python for the new words it shows up in the text file but it does not display "word found" when i run it for a second time. Any idea for this?
word = input("Please enter a word: " ).lower()
dictionary = open("Dictionary.txt","r")
if word in dictionary:
print("word found")
else:
dictionary = open("Dictionary.txt","a")
dictionary.write(word)
dictionary.write("\nThis sentence contains" + " " + word)
dictionary.close()
You have a few things you need to be careful of. I made an assumption to get a working example that the words are stored on individual lines. I also read them in and remove and leading or trailing whitespace so the match can work
word = input("Please enter a word: ").lower()
dictionary = open("Dictionary.txt", "r")
words = [x.strip() for x in dictionary.readlines()]
if word in words:
print("word found")
else:
appending_handle = open("Dictionary.txt", "a")
appending_handle.write("\n" + word)
appending_handle.close()
dictionary.close()
I also made a new variable to store the second dictionary open. Otherwise you will never close the original because you've lost the reference.
It's also not clear you want to do this at all
dictionary.write("\nThis sentence contains" + " " + word)
since it adds these to the dictionary
Try using:
if word in dictionary == True:
print("Word found")
To note: Some classmates told me that I HAVE to take userInput to create another list based on the userInput. (Eg: Input "g", Creates list with countries that starts with "g".)
This is my current code.
countries = []
population = []
str = []
path = "E:\\SCRIPTING\\Countries.txt"
obj = open(path, "r")
allList = obj.readlines()
obj.close()
userI = input("Please input a single letter: ")
if userI.isalpha():
if len(userI) > 1:
print("Please enter only a single letter.")
else:
print("continue")
elif userI.isdigit():
int(userI)
print("Please enter a single letter, not a number.")
else:
print("Please make sure that you enter a single letter.")
So far from what I have I know that it's reading my .txt file, and displaying different errors/messages when incorrect inputs are given.
(Program to be put under the else: print("continue) since its my checkpoint.
The program is made to accept only 1 letter and print all lines which start with that letter.
You could return a list with a simple test, just before your :
print("continue")
You could add those lines
listToBeDisplayed = [line for line in allList if line.startswith(userI)]
for line in listToBeDisplayed :
print line
You are not actually applying the main logic, you have done the input handling, file opening correctly.
You need:
else:
# Bad variable name, see python.org/dev/peps/pep-0008/#id36
for line in allList
if line.startswith(userI):
print line
elif userI.isdigit():
UPDATE:
There is one more change I suggest, after looking at your updated code:
# raw_input() instead of input()
userI = raw_input("Please input a single letter: ")
Apart from that, I have tested your code and it works provided that there is text data in the file pointed by path. Also another note, startswith is case sensitive, so make sure you give alphabet in correct case as the text in file.
So I am trying to store a single word to a file (which i have already managed to figure out how to do). The program would then repeat and ask me to input another word. It should check if this word already exists in the file (which it should). I have it to the point where i have inputted a word and it has stored it in the file but when i input the same word again it doesn't realise that the word already exists in the file. (This is all in a def function so when i say the next time it goes round i mean the next time i call the function)
Here is the code:
def define():
testedWord = subject
lineNumber = 1
lineInFile = "empty"
exists = False
while lineInFile != "":
wordsFile = open("Words.txt", "a")
lineInFile = linecache.getline("Words.txt", lineNumber)
lineNumber = lineNumber + 1
lineInFile = lineInFile.replace("\n", "")
if lineInFile == subject:
definitionNumber = lineNumber
exists = True
if exists == False:
wordsFile.write(testedWord)
wordsFile.write("\n")
wordsFile.close()
subject = input("")
define()
##This whole thing basically gets repeated
Like i said, if i store a new word and then in the same program try and put in the same word again then it won't recognize that it has already stored this word. When i stop the program and restart it, it works (but i dont want to have to do that)
Thanks for you help (if it is possible to help lol)
Dan
I think you're making (almost) everything more complicated than it needs to be. Here is a different way of doing what you're trying to do:
def word_check(f_name, word):
with open(f_name) as fi:
for line in fi: # let Python deal with line iteration for you
if line.startswith(word):
return # return if the word exists
# word didn't exist, so reopen the file in append mode
with open(f_name, 'a') as fo:
fo.write("{}\n".format(word))
return
def main():
f_name = "test.txt"
with open(f_name, 'w') as fo:
pass # just to create the empty file
word_list = ['a', 'few', 'words', 'with', 'one',
'word', 'repeated', 'few'] # note that 'few' appears twice
for word in word_list:
word_check(f_name, word)
if __name__ == "__main__":
main()
This produces an output file with the following text:
a
few
words
with
one
repeated
In this example, I just created a list of words instead of using input to keep the example simple. Note how inefficient your current method is, though. You're reopening a file and reading every line for every word entered. Consider building your word list in memory instead, and writing it out at the end. Here's an implementation that takes advantage of the built-in set datatype. They don't allow repeated elements. If you're okay with writing out the file at the end of the program run instead of on-the-fly, you can do this instead:
def main():
word_set = set()
while True:
word = input("Please enter a word: ")
if word == 'stop': # we're using the word 'stop' to break from the loop
break # this of course means that 'stop' should be entered
# as an input word unless you want to exit
word_set.add(word)
with open('test.txt', 'w') as of:
of.writelines("{}\n".format(word) for word in word_set)
# google "generator expressions" if the previous line doesn't
# make sense to you
return
if __name__ == "__main__":
main()
Printed output:
Please enter a word: apple
Please enter a word: grape
Please enter a word: cherry
Please enter a word: grape
Please enter a word: banana
Please enter a word: stop
Produces this file:
grape
banana
cherry
apple
Not sure what im doing wrong here? the program asks for file name and reads the file but when it come to printing the encoded message it comes up blank. What am I missing, as if I change the phrase to just normal raw_input("enter message") the code will work, but this is not reading from the txt file.
letters = "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
cshift = int(input("Enter a number: "))
phrase = open(raw_input("file name: "), 'r')
newPhrase = ""
for l in phrase:
if l in letters:
pos = letters.index(l) + cshift
if pos > 25:
pos = pos-26
newPhrase += letters[pos]
else:
newPhrase += " "
print(newPhrase)
The problem here is that the for-loop on this line:
for l in phrase:
will return complete lines, not individual characters.
As such you will have to loop through individual characters from those lines as well, or read the file binary, or use functions on the file object that will read one character at a time.
You could simply do this:
for line in phrase:
for l in line:
... rest of your code here
The open function does not return a string, but a handle to the opened file from which strings can be read. You should search for information on how to read a file into a string in Python and then try it in a REPL to make sure it returns a string and not something else.
I need assistance for this problem I'm having. I'm trying to get my program to grab the first Letter from the first Word on every single line and print them in a single string.
For example if I type the following words in a block of text:
People like to eat pie for three reasons, it tastes delicious. The taste is unbelievable, next pie makes a
great dessert after dinner, finally pie is disgusting.
The result should be "Pg" this is a small example but you get the idea.
I started on the code but I'm clueless on where to go.
#Prompt the user to enter a block of text.
done = False
print("Enter as much text as you like. Type EOF on a separate line to finish.")
textInput = ""
while(done == False):
nextInput= input()
if nextInput== "EOF":
break
else:
textInput += nextInput
#Prompt the user to select an option from the Text Analyzer Menu.
print("Welcome to the Text Analyzer Menu! Select an option by typing a number"
"\n1. shortest word"
"\n2. longest word"
"\n3. most common word"
"\n4. left-column secret message!"
"\n5. fifth-words secret message!"
"\n6. word count"
"\n7. quit")
#Set option to 0.
option = 0
#Use the 'while' to keep looping until the user types in Option 7.
while option !=7:
option = int(input())
#I have trouble here on this section of the code.
#If the user selects Option 4, extract the first letter of the first word
#on each line and merge into s single string.
elif option == 4:
firstLetter = {}
for i in textInput.split():
if i < 1:
print(firstLetter)
You can store the inputs as a list, then get the first character from each list:
textInput = []
while(done == False):
nextInput= input()
if nextInput== "EOF":
break
else:
textInput.append(nextInput)
...
print ''.join(l[0] for l in textInput)
I'd start by making a list of lines instead of a single string:
print("Enter as much text as you like. Type EOF on a separate line to finish.")
lines = []
while True:
line = input()
if line == "EOF":
break
else:
lines.append(line)
Then, you can get the first letters with a loop:
letters = []
for line in lines:
first_letter = line[0]
letters.append(first_letter)
print(''.join(letters))
Or more concisely:
print(''.join([line[0] for line in lines]))
This is very simple:
with open('path/to/file') as infile:
firsts = []
for line in infile:
firsts.append(line.lstrip()[0])
print ''.join(firsts)
Of course, you could do the same thing with the following two-liner:
with open('path/to/file') as infile:
print ''.join(line.lstrip()[0] for line in infile)
Hope this helps