First off thank you for your time and answers. My task is to have my program open a text file, read its data so every word is a different string, and creating a HTML document displaying each one of these strings into a random color. So pretty much it wants us to take every word from a text file change each word into a random color and create a HTML document out of it. This is the code i have so far:
import random
def main():
filename = input("Enter Text File:")
infile = open(filename, "r")
filename2 = input("Enter HTML Document:")
outfile = open(filename2, "w")
print("<html>", file=outfile)
print(" <head>", file=outfile)
print(" </head>", file=outfile)
print(" <body>", file=outfile)
filestring = infile.read()
file = filestring.split()
filelength = len(file)
num = int(random.uniform(0,256))
num1 = int(random.uniform(0,256))
num2 = int(random.uniform(0,256))
i = 0
for i in range(filelength):
r = num
g = num1
b = num2
rgb = "{0:02X}{1:02X}{2:02X}".format(r, g, b)
print(' <span style="color:#{0}">{1}</span>'.format(rgb, file[i]),file=outfile)
i = 0 + 1
print(" </body>", file=outfile)
print("</html>", file=outfile)
main()
This code works but it does not change each individual word into a random color it just changes all the words into the same color. I appreciate the answers.
Since this is homework, I'll limit my answer to a hint:
You're currently generating one random colour, and applying it to every word. What you should be doing is generating a new random colour for every word.
this code should be in the loop (for i in range(filelength):)
num = int(random.uniform(0,256))
num1 = int(random.uniform(0,256))
num2 = int(random.uniform(0,256))
Your code (I haven't executed it) seems to be correct(ignoring the absence of Exception Handling). You need to change num, num1 and num2 for each word. That would mean, you need to put num, num1 and num2 inside the loop for i in range(filelength):.
Try this:
import random
def main():
filename = input("Enter Text File:").strip()
infile = open(filename, "r")
filename2 = input("Enter HTML Document:").strip()
outfile = open(filename2, "w")
print("<html><head></head><body>",file=outfile)
for line in infile:
for word in line.split():
(r,g,b)=[int(random.uniform(0,256)) for x in range(3)]
rgb = "{0:02X}{1:02X}{2:02X}".format(r, g, b)
print(' <span style="color:#{0}">{1} </span>'.format(rgb,word),file=outfile)
print("<br>",file=outfile)
print(" </body>", file=outfile)
print("</html>", file=outfile)
main()
Related
How can I write a find_lines() function that prompts the user for a file and a string, and uses the find_matching_lines function to print the lines where the string was found.
Can rewrite mine second function to work?
Here is my code for both functions:
1)
def find_matching_lines(h,s):
list = []
line_number = -1
for line in h:
line_number += 1
if s in line:
list.append((line_number, line.rstrip()+'\n'))
return list
hinfile = open('infile.txt')
print(find_matching_lines(hinfile, 'the mob'))
hinfile.close()
hinfile = open('infile.txt')
print(find_matching_lines(hinfile, 'the'))
hinfile.close()
with open('infile.txt') as h:
print(find_matching_lines(h, 'sommar'))
def find_lines():
answer = input('Hello, which file do you want to search in?')
while answer != 'infile.txt':
answer = input('Hello, which file do you want to search in?')
print('Ok, searching in "infile.txt"')
answer2 = input('What do you want to search for?')
answer3 = find_matching_lines(answer, answer2)
for i in answer3:
print(f"Line {i[0]}: {i[1]}")
find_lines()
I am trying to call the list I created in a sub-function, into another sub-function. Using parameters and call functions are my Achilles heel as it relates to python. I want to call the newList I created in the calculateZscore function, into mu globalChi function.
My current code:
import os
import math
'''
c:/Scripts/Lab2Data
NCSIDS_ObsExp.txt
chisquare.txt
output.txt
'''
def main():
directory = raw_input ("What is the working directory? ")
input_file = raw_input ("What is the name of the input file? ")
chiTable = raw_input ("What is the name of the chi-squared table? ")
outPut = raw_input ("What is the name of the output file? ")
path = os.path.join(directory,input_file)
path_1 = os.path.join(directory, chiTable)
path_2 = os.path.join(directory, outPut)
if __name__ == "__main__":
main()
def calculateZscore(inFileName, outFileName):
inputFile = open(inFileName,"r")
txtfile = open(outFileName, 'w')
for line in inputFile:
newList = line.strip().split(',')
obsExp = newList[-2:]
obsExp = list(map(int, obsExp))
obs = obsExp[0]
exp = obsExp[1]
zScore = (obs - exp) / math.sqrt(exp)
zScore = map(str, [zScore])
newList.extend(zScore)
txtfile = open(outFileName, 'w')
txtfile.writelines(newList)
inputFile.close() #close the files
txtfile.close()
return newList #return the list containing z scores
def globalChi(zscoreList):
print newList
You should read about the return statement. It is used to make a function return a result (the opposite of taking an argument), and cannot be used outside a function.
Here, you are doing the exact opposite.
I'm very new to Python and having a problem with a program I'm doing for a class. main() and create_file work, but when it gets to read_file, the interpreter just sits there. The program is running but nothing is happening.
The answer is probably something very simple, but I just can't see it. Thanks in advance for any help.
I'm using IDLE (Python and IDLE v. 3.5.2)
Here's the code:
import random
FILENAME = "randomNumbers.txt"
def create_file(userNum):
#Create and open the randomNumbers.txt file
randomOutput = open(FILENAME, 'w')
#Generate random numbers and write them to the file
for num in range(userNum):
num = random.randint(1, 500)
randomOutput.write(str(num) + '\n')
#Confirm data written
print("Data written to file.")
#Close the file
randomOutput.close()
def read_file():
#Open the random number file
randomInput = open(FILENAME, 'r')
#Declare variables
entry = randomInput.readline()
count = 0
total = 0
#Check for eof, read in data, and add it
while entry != '':
num = int(entry)
total += num
count += 1
#Print the total and the number of random numbers
print("The total is:", total)
print("The number of random numbers generated and added is:", count)
#Close the file
randomInput.close()
def main():
#Get user data
numGenerate = int(input("Enter the number of random numbers to generate: "))
#Call create_file function
create_file(numGenerate)
#Call read_file function
read_file()
main()
You have an infinite while loop in the function, since entry never changes during the loop.
The Pythonic way to process all the lines in a file is like this:
for entry in randomInput:
num = int(entry)
total += num
count += 1
I am writing a program that will open a specified file then "wrap" all lines that are longer than a given line length and print the result on the screen.
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r+')
file = openFile.read()
lLength = int(input("enter a number between 10 & 20: "))
while (lLength < 10) or (lLength > 20) :
print("Invalid input, please try again...")
lLength = int(input("enter a number between 10 & 20: "))
wr = textwrap.TextWrapper()
wr.width = lLength
wr.expand_tabs = True
wraped = wr.wrap(file)
print("Here is your output formated to a max of", lLength, "characters per line: ")
print(wraped)
main()
When I do this instead of wrapping it prints everything in the file as a list with commas and brackets, instead of wrapping them.
textwrap.TextWrapper.wrap "returns a list of output lines, without final newlines."
You could either join them together with a linebreak
print('\n'.join(wrapped))
or iterate through and print them one at a time
for line in wrapped:
print(line)
fileName = raw_input("Enter the filename: ")
n = input("Enter the line you want to look: ")
f = open(fileName,'r')
numbers = []
for line in f:
sentenceInLine = line.split('\n')
for word in sentenceInLine:
if word != '':
numbers.append(word)
print numbers
print len(numbers)
print numbers[n-1]
if n == 0:
print "There is no 0 line"
break
i think you missed to split sentenceInLine like sentenceInLine.split(' ')
You are looping over each line, then you split lines based on '\n'. That \n is a line break character. That would confuse your logic right there.
So it is a bit confusing what you are trying to do but you should check n after the user has inputed a value for n. not at the end.
You may want to also catch the exception where file cannot be found I think this is what you need:
fileName = raw_input("Enter the filename: ")
n = input("Enter the line you want to look: ")
if n == 0:
print "There is no 0 line"
sys.exit();
try:
f = open(fileName,'r')
except IOError:
print "Could not find file"
sys.exit()