Trying to add text from a random line from a text file - python-3.x

I am making a game in pygame for my sister for practising in pygame and I am trying to add a random line from a text file in to window name:
import pygame,random,sys
RandomMess = open('GameText.txt')
pygame.display.set_caption('Dream Land: {}').
#The .txt file currently has 4 lines but will be a lot more in the future...
#These are the test lines: This is in beta, hi :), hello, hi
I have all the rest of the code in case anyone says that I haven't done any other code to make the window or anything.
I want it to say: Dream Land: {} then in the braces add a random line from the file.

You're looking for readlines() and random.choice().
import random,sys
RandomMess = open('GameText.txt')
# .readlines() will create a list of the lines in the file.
# So in our case ['This is in beta', 'hi :)', 'hello', 'hi']
# random.choice() then picks one item from this list.
line = random.choice(RandomMess.readlines())
# Then use .format() to add the line into the caption
pygame.display.set_caption('Dream Land: {}'.format(line))

Related

How to select every line in tkinter except of which start with a specific word in tkinter?

I need to select every line (not copy, so highlight all with the blue selection thing) except which start with CONTROLBAR (it will pass the lines which start with that word). Is there I way to do that, please?
Note: I am trying to that to a text widget:
text = Text(root, height=Window_sizeX, width=Window_sizeY, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set, font = (FontContainer, 11), wrap='none', undo=True, autoseparators=True)
text.pack()
The files which I want to use that code are files special to a game, the commands which need not be changed start with CONTROLBAR while others which am trying to copy and translate are just below them and in double-quotes, first, I tried to use re to at least extract the words between double quotes but it didn't work because those files have over 100,000 lines and by the time python extracts it all, it takes too much time. That's why I want to select them then copy with ctrl+c and paste to a translator, get the result and paste them over the selected so only the words in double quotes (strings) will be translated, commands will stay as they are.
There's one of those string files specific to the game: https://drive.google.com/file/d/1vc8Ah49duA8lMJbK4bV3ZGG5W1r1n4qX/view?usp=sharing
Edit: I forgot to say that there's also ENDs which need not be changed
def opn():
global file
text.delete(1.0 , END)
with open(askopenfilename() , 'r', encoding=DefaultEnco) as file:
if file != '':
global txt
txt = file.read()
text.insert(INSERT,txt)
else:
pass
def SelectAllQuotes():
global txt, file
for line in txt:
if line.startswith(str(('"'))) and line.endswith(str(('"'))):
text.focus()
text.tag_add("sel", line)
text.clipboard_clear()
text.clipboard_append(text.selection_get())
print('copied')
``` i made this code but it gives this error:
```Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\SERCE\Desktop\TEST2\Shadow's Bfme Editor - Copy (2).py", line 740, in SelectAllQuotes
text.tag_add("sel", line)
File "C:\Python\Python38-32\lib\tkinter\__init__.py", line 3825, in tag_add
self.tk.call(
_tkinter.TclError: bad text index """

How do I get a random line from an external txt file?

So, I'm trying to answer a coding question. It's supposed to create a random knock knock joke from an external text file, but I can't figure out how to get the joke randomized. It just prints the first joke.
The below is my code:
# Saving filepath to a variable
# makes a smoother transition to the Sandbox
filepath = "KnockKnock.txt"
# When finished copy all code after this line into the Sandbox
# Open the file as read-only
inFile = open(filepath, "r")
# Get the first line and do something with it
line = inFile.readline()
# Write your program below
print("Knock-Knock")
print("Who's there?")
print (line)
print(line + "who?")
line = inFile.readline()
print(line)
line = inFile.readline()
inFile.close()
Any idea how to get a random joke instead of it just doing the first one in the file?
Assuming your file KnockKnock.txt has the jokes in pairs, every other line, then we can read all of the jokes into a list of 2-tuples, containing the setup and punchline.
import random
...
# read in file and make a list of jokes
with open('KnockKnock.txt', 'r') as infile:
# make a list of lines from file
in_lines = infile.readlines()
# pair every line with every other line - setup and punchline
jokes = list(zip(in_lines[0::2], in_lines[1::2]))
# choose a random joke
setup, punchline = random.choice(jokes)
# print the joke
print("Knock-Knock")
print("Who's there?")
print(setup)
print(setup + " who?")
print(punchline)

printing sentence from a word search

As an exercise in the code below, I've copied and saved Rice's Tarzan novel into a text file (named tarzan.txt) and within it, I've searched for "row" and printed out the corresponding lines.
Is it difficult to modify this code so that it searches for the word "row" rather than instances of these letters appearing in another word AND it prints the sentence that contain this word rather than simply the line it appears in? Thanks.
PS - in the code below, I couldn't get lines 3, 5, and 6 to indent properly, despite the 4 space suggestion
a="tarzan.txt"
with open (a) as f_obj:
contents=f_obj.readlines()
for line in contents:
if "row" in line:
print(line)
import re
a="tarzan.txt"
with open (a) as f_obj:
contents=f_obj.readlines()
for line in contents:
if re.search(r'\brow\b',line): ####### search for 'row' in line
print contents.index(line) ####### print line number
Here \b means word boundries.

User input after file input in Python?

First year Comp Sci student here.
I have an assignment that is asking us to make a simple game using Python, which takes an input file to create the game-world (2D grid). You're then supposed to give movement commands via user input afterwards. My program reads the input file one line at a time to create the world using:
def getFile():
try:
line = input()
except EOFError:
line = EOF
return line
...after which it creates a list to represent the line, with each member being a character in the line, and then creates a list containing each of these lists (amounting to a grid with row and column coordinates).
The thing is, I later need to take input in order to move the character, and I can't do this because it still wants to read the file input, and the last line from the file is an EOF character, causing an error. Specifically the "EOF when reading a line" error.
How can I get around this?
Sounds like you are reading the file directly from stdin -- something like:
python3 my_game.py < game_world.txt
Instead, you need to pass the file name as an argument to your program, that way stdin will still be connected to the console:
python3 my_game.py game_world.txt
and then get_file looks more like:
def getFile(file_name):
with open(file_name) as fh:
for line in fh:
return line
File interaction is python3 goes like this:
# the open keyword opens a file in read-only mode by default
f = open("path/to/file.txt")
# read all the lines in the file and return them in a list
lines = f.readlines()
#or iterate them at the same time
for line in f:
#now get each character from each line
for char_in_line in line:
#do something
#close file
f.close()
line terminator for the file is by default \n
If you want something else you pass it as a parameter to the open method (the newline parameter. Default=None='\n'):
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

String search and write into a file in jython

I wish to write a program that can read a file and if a particular str_to_find is found in a bigger string, say
"AACATGCCACCTGAATTGGATGGAATTCATGCGGGACACGCGGATTACACCTATGAGCAGAAATACGGCCTGCGCGATTACCGTGGCGGTGGACGTTCTTCCGCGCGTGAAACCGCGATGCGCGTAGCGGCAGGGGCGATCGCCAAGAAATACCTGGCGGAAAAGTTCGGCATCGAAATCCGCGGCTGCCTGACCCAGATGGGCGACATTCCGCTGGAGATTAAAGACTGGCGTCAGGTTGAGCTTAATCCGTTTTC"
then write that line and the above line of it into the file and keep repeating it for all the match found.
Please suggest the solution. I have written the program for printing that particular search line but I don't know how to write the above line.
import re
import string
file=open('C:/Users/Administrator/Desktop/input.txt','r')
output=open('C:/Users/Administrator/Desktop/output.txt','w')
count_record=file.readline()
str_to_find='AACCATGC'
while count_record:
if string.find(list,str_to_find) ==0:
output.write(count_record)
file.close()
output.close()
one way
for line in open("file"):
if "str_to_find" in line:
print prev
print line.rstrip()
prev=line.rstrip()

Resources