Delete a line from imported text file string - python

I have imported two text files into my program-
f = open("words.txt","r")
words = f.read()
f = open("solved.txt","r")
solved = f.read()
and they are involved in a 'Guess the Word' game I am making.
At the end of the game, the program checks the users answers against the real ones...
print('Checking words...')
sleep(2)
if (words) == (solved):
print('>Well done!')
sleep(1)
print('>All of your answers are right')
else:
print('Not quite, keep trying!')
sleep(1)
menu()
The words text file has an extra carriage return on the end of the string, so no matter what the user makes the words string, it will never be exactly the same as the solved string (with no carriage return on the end), and therefore the user can NEVER win the game.
I HAVE the edit the text files within the program only, so I would like a way to delete the extra carriage return from the end of the words string, so that the user CAN win the game.
Words.txt-
#+/084&"
#3*#%#+
8%203:
,1$&
!-*%
.#7&33&
#*#71%
&-&641'2
#))85
9&330*
Theres an extra space here
Solved.txt-
ACQUIRED
ALMANAC
INSULT
JOKE
HYMN
GAZELLE
AMAZON
EYEBROWS
AFFIX
VELLUM
-Alastair

def getwords(file_name):
with open(file_name) as file:
for word in file:
word = word.strip()
if word: yield word
words = list(getwords("words.txt"))
solved = list(getwords("solved.txt"))
... # do anything with 'words' and 'solved' #...

Related

How to update a list when using for loops in python

Im am making a program that is designed to solve word searches using functions. The output I get from the function find_horizontal
is:
['********RRIRAI', 'FUNCTIONRRIRAI', 'RAIOONFRCCPWON', 'PTCSNOBEUITOLO', 'BNCACIANTOSLIH', 'RBYOLILYNREFBT', 'HYYNOGESTIBRIY', 'AATTSIONCMCENP', 'UORTENRRCBFVAU', 'CEBEECVWIERORI', '*********TOPYF', 'PROCESSORTOPYF', 'OH********HSOS', 'OHCOMPUTERHSOS', 'YCYPRESREOSMRW', 'OATHBRMVTHHCTR', 'PGORWOOUIPSCHP']
The problem is that it has added the line to the list Outpuz once with the found word crossed out and then secondly before it was crossed out. My desired output is:
['********RRIRAI', 'RAIOONFRCCPWON', 'PTCSNOBEUITOLO', 'BNCACIANTOSLIH', 'RBYOLILYNREFBT', 'HYYNOGESTIBRIY', 'AATTSIONCMCENP', 'UORTENRRCBFVAU', 'CEBEECVWIERORI', '*********TOPYF', 'OH********HSOS', 'YCYPRESREOSMRW', 'OATHBRMVTHHCTR', 'PGORWOOUIPSCHP']
Here is my full code:
if __name__ == '__main__':
Puzzle = ["FUNCTIONRRIRAI",
"RAIOONFRCCPWON",
"PTCSNOBEUITOLO",
"BNCACIANTOSLIH",
"RBYOLILYNREFBT",
"HYYNOGESTIBRIY",
"AATTSIONCMCENP",
"UORTENRRCBFVAU",
"CEBEECVWIERORI",
"PROCESSORTOPYF",
"OHCOMPUTERHSOS",
"YCYPRESREOSMRW",
"OATHBRMVTHHCTR",
"PGORWOOUIPSCHP"]
def load_words_to_find(file_name):
word_list = []
file = open(file_name, "r")
for line in file.readlines():
word_list.append(line)
word_list = list(map(lambda s: s.strip(), word_list))
return word_list
def find_horizontal(Puzzle, Words, ReplaceWith, Found):
# Parameters :- List:Puzzle, List:Words, Character:ReplaceWith, List:Found
# Return :- List:Outpuz, List:Found
# Find all words which are horizontally in place (left to right and right to left), return the puzzle and list of found words
add = True
Outpuz = []
for line in Puzzle:
for word in Words:
if word in line:
Found.append(word)
print("Found: ", word)
Outpuz.append(line.replace(word,ReplaceWith*len(word)))
add = False
if not add:
pass
elif add:
Outpuz.append(line)
Outpuz.append(line)
print(Outpuz)
return Outpuz, Found
find_horizontal(Puzzle, load_words_to_find("words.txt"), "*", [])
I did something very similar about a year ago.
https://github.com/BenMcLean981/Python-Wordsearch
I think the issue is Outpuz.append(line) is just adding every line from puzzle to output.
What is in your filename? What is found and Outpuz supposed to be? Found I guess is the list of word from words that it has found in puzzle. But then whats outpuz?
Id change it from this:
if word in line:
Found.append(word)
print("Found: ", word)
Outpuz.append(line.replace(word,ReplaceWith*len(word)))
add = False
if not add:
pass
elif add:
Outpuz.append(line)
Outpuz.append(line
Outpuz.append(line)
to this:
if word in line:
Found.append(word)
print("Found: ", word)
Outpuz.append(line.replace(word,ReplaceWith*len(word)))
#Adds the line if it has the change
else:
Outpuz.append(line) #Adds the line if it doesnt have the change.

Python Can't load .txt file

photo
This code can't load the log.txt file.
The file is in the temp folder.
Why can't I load it?
This code only displays the text: Search word: ABC.
text = input("Search word: ABC")
with open("C:\Temp\log.txt", encoding = "utf-8") as f:
cnt = 0
for line in f:
l = line.strip().split()
if (l[-1] == text):
print(line.strip())
cnt += 1
if (cnt): print(cnt, "count")
else: print(text, "No data.")
It seems like you need to type the word after running the program. The "ABC" you see is the prompt from the script i.e. it is not entered by you. That's why the program keeps running, waiting for the input and doesn't go further.
Here's your code slightly modified to make it clear.
text = input("Search word: ")
with open("C:\Temp\log.txt", encoding="utf-8") as f:
cnt = 0
for line in f:
if text in line:
print(line.strip())
cnt += 1
if cnt:
print(cnt, "count")
else:
print(text, "No data.")
I guess you understand that your code:
ask the user to input some text
count the occurrences of that text in the file C:\Temp\log.txt, under the conditions:
the text does not contains space
the text is at the end of the line
the text may be followed by one or more spaces
the text must be preceded by one or more spaces
the file cannot have empty lines
Under those conditions, your code should behave nicely. I would recommend to change text = input("Search word: ABC") to text = input("Search word: ") to make it clear that the user need to input some text.
If you still have unexpected results, check if you don't have any character encoding issue (like a terminal default encoding not being utf-8)

Automate the boring stuff with python chapter_8 MadLibs

Hello this exercise says:
Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file.
textfile = The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unnafected by these events.
What I have so far is :
import re
#filename = input('Input the Filename: ')
with open('madlibs.txt') as file:
content = file.read()
file.close()
regex = re.compile(r'ADJECTIVE|NOUN|VERB|ADVERB')
#regex = re.compile('[A-Z]{3,}')
matches = regex.findall(content)
#newWord = []
for word in matches:
user_input = input('Enter %s: ' % word)
# newWord.append(user_input)
new_content = content.replace(word,user_input,1)
print(new_content)
My input is:
Enter ADJECTIVE: heavy
Enter NOUN: whale
Enter VERB: runs
Enter NOUN: door
And my output:
The ADJECTIVE panda walked to the door and then VERB. A nearby door was
unnafected by these events.
Can someone explain to me what I'm doing wrong? It seems that I can't change ADJECTIVE and VERB for some reason, i also tried the commented regex with uppercase and it does the same so the problem is somewhere else.
You need to change content, but because you aren't, it's overwriting your changes until the very last word:
for word in matches:
user_input = input('Enter %s: ' % word)
content = content.replace(word,user_input) # overwrite content here
print(content)
Or, if you prefer to keep content the same:
new_content = content
for word in matches:
user_input = input('Enter %s: ' % word)
new_content = new_content.replace(word,user_input) # overwrite new_content here
print(new_content)
Strings in python are immutable, meaning that they will not be changed in-place, and instead must be re-assigned:
somestring = "this is a string"
for word in ["is", "a"]:
newstring = somestring.replace(word, "aaaa")
print(newstring)
# this is aaaa string
print(somestring)
# this is a string
Note that somestring is still the original value. The first replace did happen, it just was overwritten when the result of somestring.replace("a", "aaaa") was reassigned.
Broken into steps:
somestring = "this is a string"
newstring = somestring.replace("is", "aaaa")
# this aaaa a string
newstring = somestring.replace("a", "aaaa")
# this is aaaa string
#! /usr/bin/python3
# mad_libs.py - Playing mad libs game
# Usage: python3 mad_libs.py save - Save a mad lib phrase from clip board
# python3 mad_libs.py - Play the mad libs game.
# Caution: Must save at least one phrase before playing.
import shelve, pyclip, random, sys, re
import pyinputplus as pyi
# Open shelve file
shelfFile = shelve.open('mad_libs')
# Add phrase to the database by pasting from clipboard
if len(sys.argv) == 2 and sys.argv[1] == 'save':
shelfFile[str(len(shelfFile))] = pyclip.paste().decode()
print("Phrase saved.")
sys.exit()
# Get a random phrase from database and display
phrase = shelfFile[str(random.randrange(len(shelfFile)))]
# Regex for finding match
matLibsRegex = re.compile(r'(ADJECTIVE)|(NOUN)|(VERB)|(ADVERB)')
print(phrase)
while True:
# Find all the matches and replace with user's input
match = matLibsRegex.search(phrase)
if match == None: # Return None if there is no match
break
prompt = f"Enter an {match.group().lower()}: " if match.group(
)[0] in 'Aa' else f"Enter a {match.group().lower()}: "
substitute = pyi.inputStr(prompt)
phrase = phrase.replace(match.group(), substitute, 1) # Replace the fill-in space with user's input
# Print the final phrase and save it to file
print(phrase)
result = open('mad_libs_result.txt', 'a')
result.write(phrase + '\n')
result.close()
shelfFile.close()
I hope this could enhance your code.
Since this post is about mad libs and I would like to drop my solutions here for upcoming learners. I combine the functionality of Mad Libs exercise and Extend Multi-Clipbaord exercise.

Combine lines when writing to file in Python?

So I'm trying to write all this info to a .txt file, but due to the names being pulled from a .txt file that goes
Liam
Noah
William
etc...
When I write to a file, it puts the first and last names on separate lines from everything else.
I've looked on StackOverflow for a solution but I couldn't find anything specific enough.
password = input('Enter the Password you would like to use ')
open('names.txt', 'r+')
lines = open("names.txt").readlines()
firstName = lines[0]
words = firstName.split()
firstNameChoice = random.choice(lines)
open('names.txt', 'r+')
lines = open("names.txt").readlines()
lastName = lines[0]
words = lastName.split()
lastNameChoice = random.choice(lines)
def signUp():
randomNumber = str(random.randint(0,10000))
accountFile = open('accounts.txt', 'a')
accountFile.write(firstNameChoice)
accountFile.write(lastNameChoice)
accountFile.write(randomNumber)
accountFile.write('#')
accountFile.write(catchall)
accountFile.write(':')
accountFile.write(password)
accountFile.write('\n')
signUp()
Expectation would be everything printed to one line but that's not the case.
As a quick fix for your problem, you could merge all writing commands in one line:
with open('accounts.txt', 'a') as accountFile: # using a context manager is highly recommended
# with spaces
accountFile.write('{} {} {} # {} : {} \n'.format(
firstNameChoice,
lastNameChoice,
randomNumber,
catchall,
password
)
)
# without spaces
accountFile.write('{}{}{}#{}:{}\n'.format(
firstNameChoice,
lastNameChoice,
randomNumber,
catchall,
password
)
)
If my understanding is right then you want to write everything in one line.
The variables you are writing containing \n while writing into the file.
So you have to replace it with a ' '. Replace this code into your program like:
accountFile.write(firstNameChoice.replace('\n',' '))
accountFile.write(lastNameChoice.replace('\n',' '))
accountFile.write(str(randomNumber).replace('\n',' '))
accountFile.write('#'.replace('\n',' '))
#accountFile.write(catchall)
accountFile.write(':'.replace('\n',' '))
accountFile.write(str(password).replace('\n',' '))
Now it will print like this WilliamWilliam448#:dsada
By the way I dont know what you mean by catchall
The reason it puts it all on a new line is because the strings of your names contains the "\n" on the end because it has an enter to a new line. There is an easy fix for this.
Where you define your first and last name variables add .rstrip() at the end. Like this:
firstNameChoice = random.choice(lines).rstrip()
lastNameChoice = random.choice(lines).rstrip()
def signUp():
randomNumber = str(random.randint(0,10000))
accountFile = open('accounts.txt', 'a')
accountFile.write(f'{firstNameChoice} {lastNameChoice} {randomNumber} # {catchall}: {password} \n')

How do I count up certain words (not just one word) in a string and then output different code if there are different amounts of words?

Sorry for lengthy question, I didn't know how to word it specifically without it being marked as a duplicate. Anyway, I am trying to count up a set of keywords that a user has inputted which is written into a text file. Here is the code:
import os
def keyword_searcher():
user_query = input("Enter your problem:\n")
with open("user_query.txt", "a+") as query:
query.write(user_query.lower())
query.seek(0)
for line in query:
for word in line.split():
if word in ("backlight", "display", "cracked", "touchscreen"):
with open("Solutions1.txt", "r") as f:
solution_one = f.read()
print ("Keyword for screen problem found:\n")
print (solution_one)
elif word in ("battery", "charger", "usb", "charge"):
with open("Solutions2.txt", "r") as f_two:
solution_two = f_two.read()
print ("Keyword for battery problem found:\n")
print(solution_two)
elif word in ("virus", "hacked", "infected", "antivirus"):
with open("Solutions3.txt", "r") as f_three:
solution_three = f_three.read()
print ("Keyword for virus problem found:\n")
print (solution_three)
else:
pass
keyword_searcher()
os.remove("user_query.txt")
My problem is, when the user inputs more than one of any keywords, it outputs the code that amount of times, when I only want it once. How do I fix this?
for word in line.split():
if word in ("backlight", "display", "cracked", "touchscreen"):
...
means that you'll check one word per iteration of the loop, so if more than one word matches, you get duplicates. To do it only when at least one of the words is present in the list, use sets:
for line in query:
words = set(line.split())
if words & {"backlight", "display", "cracked", "touchscreen"}:
...
Alternatively, you could do something like
for line in query:
words = line.split()
if any(word in ("backlight", "display", "cracked", "touchscreen") for word in words):
...
which may be easier to read but would be slower.
You can really slim this program down. There is no need to write the user input to a file and remove it at the end, just store it as a variable. You should check every statement with an if statement to ensure it checks each one. Also, the else: pass is redundant. Hopefully this helps you out, good luck with your program:
list_one = ["backlight", "display", "cracked", "touchscreen"]
list_two = ["battery", "charger", "usb", "charge"]
list_three = ["virus", "hacked", "infected", "antivirus"]
user_query = input("Enter your problem:\n").split()
if any(word in list_one for word in user_query):
with open("Solutions1.txt") as f:
solution_one = f.read()
print("Keyword for screen problem found:\n")
print(solution_one)
if any(word in list_two for word in user_query):
with open("Solutions2.txt") as f_two:
solution_two = f_two.read()
print("Keyword for battery problem found:\n")
print(solution_two)
if any(word in list_three for word in user_query):
with open("Solutions3.txt") as f_three:
solution_three = f_three.read()
print("Keyword for virus problem found:\n")
print(solution_three)

Categories