I have a text file with 2000 words, one word on each line. I'm trying to create a code that prints out two random words from the textfile on the same line every 10 seconds. The beginning part of my text file is shown below:
slip
melt
true
therapeutic
scarce
visitor
wild
tickle
.
.
.
The code that I've written is:
from time import sleep
import random
my_file = open("words.txt", "r")
i = 1
while i > 0:
number_1 = random.randint(0, 2000)
number_2 = random.randint(0, 2000)
word_1 = my_file.readline(number_1)
word_2 = my_file.readline(number_2)
print(word_1.rstrip() + " " + word_2.rstrip())
i += 1
sleep(10)
When I execute the code instead of printing two random words it starts printing all the words in order from the top of the text. I'm not sure why this is happening since number_1 and number_2 are inside the loop so every time two words print number_1 and number_2 should be changed to two other random numbers. I don't think replacing number_1 and number_2 outside of the loop will work either since they'll be fixed to two values and the code will just keep on printing the same two words. Does anyone know what I can do to fix the code?
readline() doesn't take any parameters and just returns the next line in your file input*. Instead, try to create a list using readlines(), then choose randomly from that list. So here, you'd make word_list = my_file.readlines(), then choose random elements from word_list.
*Correction: readline() does take a parameter of the number of bytes to read. The documentation for the function doesn't seem to explicitly state this. Thanks E. Ducateme!
my_file.readline(number_1) does not do what you want. The argument for readline is the max size in bytes of a line you can read rather than the position of the line in the file.
As the other answer mentioned, a better approach is to first read the lines into a list and then randomly select words from it:
from time import sleep
import random
my_file = open("words.txt", "r")
words = my_file.readlines()
i = 1
while i > 0:
number_1 = random.randint(0, 2000)
number_2 = random.randint(0, 2000)
word_1 = words[number_1]
word_2 = words[number_2]
print(word_1.rstrip() + " " + word_2.rstrip())
i += 1
sleep(10)
Related
I want to print two labels that have the same numbers on them. I am using ZPL. I have already made my print format in ZPL and it works properly. I am trying to print a data range. For example:
"What is the first number in the range?" User inputs 100
"What is the second number in the range?" User inputs 120
I would then get 40 labels in order.
I then want it to export that data into a notepad file and then print it to my default printer. My problem is that to print with ZPL I have to "tag" my data range with my ZPL code. I cant figure out how to get my data range to go into my print statement correctly. Please help. Thank you in advance!
import os
import sys
start = int(input("Enter the start of range: "))
end = int(input("Enter the end of range: "))
with open('TestFile.txt', 'a') as sys.stdout:
print('^XA')
print('^PQ2')
for labelRange in range(start, end + 1):
print('^FO185,50^A0,300^FD')(labelRange, end = " ")('^FS')
#print('\n')
print('^XZ')
os.startfile("C:/Users/joe.smith/desktop/TestFile.txt", "print")
exit()
here is something to get you started, but I doubt it is complete. You will need to provide a valid ZPL file for making the changes.
I also made the program use fixed numbers for now and so it just runs and outputs.You can change it back once you have it working.
start = 110
end = 111
notepad = ''
# these are header lines that go once (if windows you might need \r\n instead of \n)
notepad += '^XA\n'
notepad += '^PQ2\n'
for label in range(start, end + 1):
# use f-strings
notepad += f'^FO185,50^A0,300^FD{label}^FS\n'
# if you need some of those other numbers to increment
# then setup a counter and do the math here inside the f-string
notepad += f'^FO185,50^A0,300^FD{label}^FS\n'
notepad += '^XZ\n'
# with open('tf.txt', 'w') as sys.stdout:
# print(notepad)
print(notepad)
exit()
outputs:
^XA
^PQ2
^FO185,50^A0,300^FD110^FS
^FO185,50^A0,300^FD110^FS
^FO185,50^A0,300^FD111^FS
^FO185,50^A0,300^FD111^FS
^XZ
I'm new to python and i have several questionable things that are happening. I am trying to figure out what i'm doing wrong with this problem:
This exercise assumes you have completed Programming Exercise 7, Random Number File
Writer. Write another program that reads the random numbers from the file, display the
numbers, and then display the following data:
• The total of the numbers
• The number of random numbers read from the file
Writing the file:
import random
def main():
randomcount = int(input('How many numbers should i generate?'))
randomfile = open('randomnumber.txt', 'w')
total = 0
for numbers in range(randomcount):
number = random.randint(1,100)
total+= number
randomfile.write((str(number)) + '\n')
randomfile.write((str(total)) + '\n')
randomfile.close()
print('File updated')
main()
output:
How many numbers should i generate?5 (enter)
file updated - **Question 1**
file updated | ---- this is new.. while doing
file updated - trial and error this started
repeating. First 2 times then
after awhile 3 times.
Refreshed kernel and outputs
still does this
reading the file: <-- #main issue
def main():
randomfile = open('randomnumber.txt','r')
contents = randomfile.readline()
while randomfile !='':
total = randomfile.readline()
contents = contents.rstrip('\n')
total = total.rstrip('\n')
print(contents)
contents = randomfile.readline()
print('total: ',total)
randomfile.close()
main()
output:
90 -
22 |
17 |--- Randomly generated
2 |
75 -
**Question 2**
<--- print('total: ', total) not showing up
-
|
|
|
. **Question 3**
. <--------- Space goes on forever like if its printing
. space. so much that theres a scroll bar just
. for empty space. if i try to scroll all the
| way to the bottom so that i can see if maybe
| its printing at the end i never reach the end
| of it because for some reason the program
- keeps adding more and more space.
The problem is that the line that writes the total is being execute each iteration. That's why there are double the number of lines as there are generated numbers.
The solution is unindenting that line, which I did here:
import random
def main():
randomcount = int(input('How many numbers should i generate?'))
randomfile = open('randomnumber.txt', 'w')
total = 0
for numbers in range(randomcount):
number = random.randint(1,100)
total+= number
randomfile.write((str(number)) + '\n')
randomfile.write((str(total)) + '\n') # <<<<<<<<<<<<<<This line was indented, it is fixed now.
randomfile.close()
print('File updated')
main()
EDIT: Fixing the read function:
def main():
randomfile = open('randomnumber.txt', 'r')
lines = randomfile.readlines()
total = 0
for line in lines:
if line is lines[-1]:
print(f"Total: {line.replace('\n', '')}") #Since the write function includes the total as the last line, you don't need to calculate here.
else:
print(line.replace('\n', ''))
main()
change readline to readlines hopefully, that should work
Clearly the issue is that in your first line you opened with a single quote ' and closed with a double quote ". Change:
def main():
randomcount = int(input('How many numbers should i generate?"))
to:
def main():
randomcount = int(input('How many numbers should i generate?'))
I restructured my code and made it a for loop instead of a while loop. You don't need to rstrip numbers that are being converted to int. Put the accumulator in the input file portion instead of the output file portion. Mae the code cleaner and it works!
import random
def main():
randomcount = int(input('How many numbers should i generate?'))
randomfile = open('randomnumber.txt', 'w')
for numbers in range(1,randomcount + 1):
numbers = random.randint(1,100)
randomfile.write(str(numbers) + '\n')
randomfile.close()
randomfile = open('randomnumber.txt','r')
total = 0
for numbers in randomfile:
numbers = int(numbers)
total+= numbers
print(numbers)
print('total',total)
main()
I am trying to make a quiz but my answers are in an external file, so but everytime I run it with my correct answers they say they are incorrect.
Here is my code:
randNum = int(random.randint(0, 4))
song = open("songList.csv","rt")
with open("songList.csv", "rt") as f:
songn = str(song.readlines()[randNum])
reader= csv.reader(f)
for row in reader:
print (songn[0])
guess = input("What is the song called?")
score = 0
correct_guess = False
while True:
if guess == songn:
correct_guess = True
break
score += 1
if score>=total:
break
song_guess = input("Incorrect! Try again:\n> ")
if correct_guess:
print("Answer correct!")
else:
print("game over")
As pointed out in the comments, you have trailing newline characters in one of the strings. Hence they aren't equal.
However I wouldn't just remove the newline. It is always good practice, if your logic allows it, to normalize strings before you test for equality. There are lots of things you can do to normalize:
def normalize(string):
string = string.strip() # Remove any leading or trailing whitespaces
string = string.lower() # Make all letters lowercase
string = " ".join(string.split()) # If the user hit spacebar twice, for example, will remove the double space. Note can have side effects.
return string
Then check
if normalize(string1) == normalize(string2):
do_something()
In fact, if you are dealing with user input, even this might not be sufficient. For example, if the user makes a typo, it won't match.
So I recommend also looking at the fuzzywuzzy library
from fuzzywuzzy import fuzz
def similar(string1, string2):
ratio = fuzz.ratio(string1, string2)
return ratio >= 85 # number between 0 and 100. Higher means fewer differences are allowed
Fuzzywuzzy is very powerful and easy to use. For more info: https://github.com/seatgeek/fuzzywuzzy
I have a file with lines of DNA in a file called 'DNASeq.txt'. I need a code to read each line and split each line at random places (inserting spaces) throughout the line. Each line needs to be split at different places.
EX: I have:
AAACCCHTHTHDAFHDSAFJANFAJDSNFADKFAFJ
And I need something like this:
AAA ADSF DFAFDDSAF ADF ADSF AFD AFAD
I have tried (!!!very new to python!!):
import random
for x in range(10):
print(random.randint(50,250))
but that prints me random numbers. Is there some way to get a random number generated as like a variable?
You can read a file line wise, write each line character-wise in a new file and insert spaces randomly:
Create demo file without spaces:
with open("t.txt","w") as f:
f.write("""ASDFSFDGHJEQWRJIJG
ASDFJSDGFIJ
SADFJSDFJJDSFJIDFJGIJSRGJSDJFIDJFG
SDFJGIKDSFGOROHPTLPASDMKFGDOKRAMGO""")
Read and rewrite demo file:
import random
max_no_space = 9 # if max sequence length without space
no_space = 0
with open("t.txt","r") as f, open("n.txt","w") as w:
for line in f:
for c in line:
w.write(c)
if random.randint(1,6) == 1 or no_space >= max_no_space:
w.write(" ")
no_space = 0
else:
no_space += 1
with open("n.txt") as k:
print(k.read())
Output:
ASDF SFD GHJEQWRJIJG
A SDFJ SDG FIJ
SADFJSD FJ JDSFJIDFJG I JSRGJSDJ FIDJFG
The pattern of spaces is random. You can influence it by settin max_no_spaces or remove the randomness to split after max_no_spaces all the time
Edit:
This way of writing 1 character at a time if you need to read 200+ en block is not very economic, you can do it with the same code like so:
with open("t.txt","w") as f:
f.write("""ASDFSFDGHJEQWRJIJSADFJSDFJJDSFJIDFJGIJSRGJSDJFIDJFGG
ASDFJSDGFIJSADFJSDFJJDSFJIDFJGIJSRGJSDJFIDJFGSADFJSDFJJDSFJIDFJGIJK
SADFJSDFJJDSFJIDFJGIJSRGJSDJFIDJFGSADFJSDFJJDSFJIDFJGIJSRGJSDJFIDJF
SDFJGIKDSFGOROHPTLPASDMKFGDOKRAMGSADFJSDFJJDSFJIDFJGIJSRGJSDJFIDJFG""")
import random
min_no_space = 10
max_no_space = 20 # if max sequence length without space
no_space = 0
with open("t.txt","r") as f, open("n.txt","w") as w:
for line in f:
for c in line:
w.write(c)
if no_space > min_no_space:
if random.randint(1,6) == 1 or no_space >= max_no_space:
w.write(" ")
no_space = 0
else:
no_space += 1
with open("n.txt") as k:
print(k.read())
Output:
ASDFSFDGHJEQ WRJIJSADFJSDF JJDSFJIDFJGIJ SRGJSDJFIDJFGG
ASDFJSDGFIJSA DFJSDFJJDSFJIDF JGIJSRGJSDJFIDJ FGSADFJSDFJJ DSFJIDFJGIJK
SADFJ SDFJJDSFJIDFJG IJSRGJSDJFIDJ FGSADFJSDFJJDS FJIDFJGIJSRG JSDJFIDJF
SDFJG IKDSFGOROHPTLPASDMKFGD OKRAMGSADFJSDF JJDSFJIDFJGI JSRGJSDJFIDJFG
If you want to split your DNA fixed amount of times (10 in my example) here's what you could try:
import random
DNA = 'AAACCCHTHTHDAFHDSAFJANFAJDSNFADKFAFJ'
splitted_DNA = ''
for split_idx in sorted(random.sample(range(len(DNA)), 10)):
splitted_DNA += DNA[len(splitted_DNA)-splitted_DNA.count(' ') :split_idx] + ' '
splitted_DNA += DNA[split_idx:]
print(splitted_DNA) # -> AAACCCHT HTH D AF HD SA F JANFAJDSNFA DK FAFJ
import random
with open('source', 'r') as in_file:
with open('dest', 'w') as out_file:
for line in in_file:
newLine = ''.join(map(lambda x:x+' '*random.randint(0,1), line)).strip() + '\n'
out_file.write(newLine)
Since you mentioned being new, I'll try to explain
I'm writing the new sequences to another file for precaution. It's
not safe to write to the file you are reading from.
The with constructor is so that you don't need to explicitly close
the file you opened.
Files can be read line by line using for loop.
''.join() converts a list to a string.
map() applies a function to every element of a list and returns the
results as a new list.
lambda is how you define a function without naming it. lambda x:
2*x doubles the number you feed it.
x + ' ' * 3 adds 3 spaces after x. random.randint(0, 1) returns
either 1 or 0. So I'm randomly selecting if I'll add a space after
each character or not. If the random.randint() returns 0, 0 spaces are added.
You can toss a coin after each character whether to add space there or not.
This function takes string as input and returns output with space inserted at random places.
def insert_random_spaces(str):
from random import randint
output_string = "".join([x+randint(0,1)*" " for x in str])
return output_string
I have found so much information from previous search on this website but I seem to be stuck on the following issue.
I have two text files that looks like this
Inter.txt ( n-lines but only showed 4 lines,you get the idea)
7275
30000
6693
855
....
rules.txt (2n-lines)
7275
8500
6693
7555
....
3
1000
8
5
....
I want to compare the first line of Inter.txt with rules.txt and in case of a match, I jump for n-lines in order to get the score of that line. (E.g. with 7275, there is a match, I jump n to get the score 3)
I produced the following code but for some reasons, I only have the ouput of the first line when I should have one for each match from my first file. With the previous example, I should have 8 as an output for 6693.
import linecache
inter = open("Inter.txt", "r")
rules = open("rules.txt", "r")
iScore = 0
jump = 266
i=0
for lineInt in inter:
#i = i+1
#print(i)
for lineRul in rules:
i = i+1
#print(i)
if lineInt == lineRul:
print("Match")
inc = linecache.getline("rules.txt", i + jump)
#print(inc)
iScore = iScore + int(inc)
print(iScore)
#break
else:
continue
All the print(i) are there because I checked that all the lines were read. I am a novice in Python.
To sum up, I don't understand why I only have one output. Thanks in advance !
Ok, I think the main thing that blocks you from getting forward is that the for loops on files gets the pointer to the end of the file, and doesn't resets when you starts the loops again.
So when you only open rules.txt once, and uses its intance in the inner loop it only goes through all the lines at the first iteration of the outer loop, the second time it tries to go over the remains lines, which are non.
The solution is to close and open the file outside the inner loop.
This code worked for me.
import linecache
inter = open("Inter.txt", "r")
iScore = 0
jump = 4
for lineInt in inter:
i=0
#i = i+1
#print(i)
rules = open("rules.txt", "r")
for lineRul in rules:
i = i+1
#print(i)
if lineInt == lineRul:
print("Match")
inc = linecache.getline("rules.txt", i + jump)
#print(inc)
iScore = iScore + int(inc)
print(iScore)
#break
else:
continue
rules.close()
I also moved where you set the i to 0 to the beginning of the outer loop, but I guess you'd find it yourself.
And I changed jump to 4 to fit the example files your gave :p
Can you please try this solution:
def get_rules_values(rules_file):
with open(rules_file, "r") as rules:
return map(int, rules.readlines())
def get_rules_dict(rules_values):
return dict(zip(rules_values[:len(rules_values)/2], rules_values[len(rules_values)/2:]))
def get_inter_values(inter_file):
with open(inter_file, "r") as inter:
return map(int, inter.readlines())
rules_dict = get_rules_dict(get_rules_values("rules.txt"))
inter_values = get_inter_values("inter.txt")
for inter_value in inter_values:
print inter_value, rules_dict[inter_value]
Hope it's working for you!