wrap all lines that are longer than line length - python

I am writing a program that limits each line to a certain length.
this is what i got so far, i am almost done but i still need to cut each line, but i cant figure it out.
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()
wraped = wr.wrap(file)
print("Here is your output formated to a max of", lLength, "characters per line: ")
wr.width = lLength
wr.expand_tabs = True
for lines in wraped:
print(lines)
Edit:
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: "))
if (lLength > 10) or (lLength < 20):
print("\nYour file contains the following text: \n" + file)
#=========================================================================
wr = textwrap.TextWrapper(width=lLength)
wraped = wr.wrap(file)
print("\n\nHere is your output formated to a max of", lLength, "characters per line: ")
for lines in wraped:
print(lines)
main()
an example of what the output SHOULD be is this.
If the file specified contains this text:
hgytuinghdt #here the length is 11
ughtnjuiknshfyth #here the length is 16
nmjhkaiolgytuhngjuin #here the length is 20
and the lLength is specified to 15 then this should print out:
hgytuinghdt
ughtnjuiknshfyt
h
nmjhkaiolgytuhng
juin

wr = textwrap.TextWrapper() should be wr = textwrap.TextWrapper(width=length, expand_tabs=True)
You should then remove wr.width = lLength and wr.expand_tabs = True. They should have been run before wr.wrap() was called, but since one can set it using keyword arguments in the TextWrapper constructor as shown at the very top, they can be removed.
PS: for lines in wraped: print(lines) can be replaced with print(wraped) if you use TextWrapper.fill.

Try this:
line = 'nmjhkaiolgytuhngjuin'
n = 5 # set the width here
a = [line[i:i+n] for i in range(0, len(line), n)]
print ("\n".join(a))

This might help you:
def wrap(f,n):
fi=open(f,"w+")
rl=fi.readlines()
for i in range(0,len(rl)):
if len(rl[i]) > n:
fi.write(rl[i][:n] +"\n" + rl[i][n:])
fi.Close()
else:
fi.write(rl[i])
fi.close()

Related

I'm getting a ValueError: cannot convert string to float: ".". What is going on?

I am trying to write a function that takes in a file with numerical values, total them all up while excluding all numbers with a letter, and find the average. However, when I try to convert a number like "3.9" to float form, I get the ValueError: cannot convert string to float: ".". I know that if I just did a straight conversion of "3.9" to float form via float("3.9") type casting it would work.
def averageSpeed():
count = 0
total = 0
stripLst = 'abcdefghijklmnopqrstuvwxyz$'
while count < 2:
try:
filename = input("Enter a file to process: ")
instance = open(filename, "r")
content = instance.readlines()
for line in content:
lineSplit = line.split()
for element in lineSplit:
for letter in element:
for character in stripLst:
if letter == character:
lineSplit.remove(element)
for line in content:
for element in line:
if float(element) > 2:
total += float(element)
print(lineSplit)
average = total / count
print(average)
break
except (FileNotFoundError):
print("That file does not exist.")
count += 1
filename = input("Enter a file name that exists: ")
averageSpeed()
File contents:
35.2
1.8
65.6
67.9z
70.2
73.2 a3.9 65.6 69.8
6$4.9
54.9
Oops, just fixed my own question with the code below:
def averageSpeed():
count = 0
total = 0
stripLst = 'abcdefghijklmnopqrstuvwxyz$'
while count < 2:
try:
filename = input("Enter a file to process: ")
instance = open(filename, "r")
content = instance.readlines()
for line in content:
print(line)
print()
for line in content:
lineSplit = line.split()
for element in lineSplit:
for letter in element:
for character in stripLst:
if letter == character:
lineSplit.remove(element)
for element in lineSplit:
if float(element) > 2:
total += float(element)
count += 1
print(lineSplit)
average = total / count
print("The total of the speeds of {} excluding all speeds with lettres in them is {}.".format(filename, total))
print("The total number of speeds in {} without letters is {}.".format(filename, count))
print("The average of the speeds of {} excluding all speeds with letters in them is {}.".format(filename, average))
break
except (FileNotFoundError):
print("That file does not exist.")
count += 1
filename = input("Enter a file name that exists: ")
averageSpeed()

Why is my function not printing the try-except-else result?

What is wrong with my code? I am not being able to retrieve data about the age range. I am working with a CSV file but having problems with the try-except-else suite. I am trying to find the average data for a given age range but am not being able to as nothing is printing.
def calculator(min_age, max_age):
file = open(r"C:\Users\alisha\OneDrive\Desktop\programming\data.csv")
data = file.read()
file.close()
#data processing
lines = data.split("\n")
del lines [-1]
#18 lines
line1 = lines[1].split(",")
line2 = lines[2].split(",")
line3 = lines[3].split(",")
line4 = lines[4].split(",")
line5 = lines[5].split(",")
line6 = lines[6].split(",")
line7 = lines[7].split(",")
line8 = lines[8].split(",")
line9 = lines[9].split(",")
line10 = lines[10].split(",")
line11 = lines[11].split(",")
line12 = lines[12].split(",")
line13 = lines[13].split(",")
line14 = lines[14].split(",")
line15 = lines[15].split(",")
line16 = lines[16].split(",")
line17 = lines[17].split(",")
line18 = lines[18].split(",")
processed = [line1, line2, line3, line4, line5, line6, line7, line8, line9, line10, line11, line12, line13, line14, line15, line16, line17, line18]
#obtain height and weight columns
age = []
for line in processed:
age.append(line[2])
min_value = min(age)
max_value = max(age)
target_weight = []
target_height = []
for line in processed:
if int(line[2]) >= min_age and int(line[2]) <= max_age:
target_weight.append(line[4])
target_height.append(line[3])
try:
calc = ((target_weight/len(target_weight)) / (target_height / len(target_height))**2 )*703
except:
if int(min_age) < int(min_value):
print("Minimum age value too small. Try Again.")
elif int(max_age) > int(max_value):
print("Maximum age value too large. Try Again.")
else:
print(f"The average for the given age range {max_age} to {min_age} is {calc}.")
sounds like your teacher wants you to create custom error classes to throw, try this:
class ValueTooHighError(Error):
pass
class ValueTooLowError(Error):
pass
file_obj = open(r"C:\Users\ahana\OneDrive\Desktop\intro toprogramming\assignment_8\patient_data.csv")
data = file_obj.read()
file_obj.close()
#----left out some code for conciseness----#
min_value = min(age)
max_value = max(age)
target_weight = []
target_height = []
for line in processed:
try:
if int(line[2]) >= min_age and int(line[2]) <= max_age:
target_weight.append(line[4])
target_height.append(line[3])
else:
if(int(line[2])<min_age):
raise ValueTooLowError
else:
raise ValueTooHighError
except:
ValueTooLowError:
print("Minimum age value too small. Try Again.")
ValueTooHighError:
print("Maximum age value too large. Try Again.")
bmi = ((sum(target_weight)/len(target_weight)) / (sum(target_height) / len(target_height))**2 )*703
print(f"The average BMI for the given age range {max_age} to {min_age} is {bmi}.")
There is a lot going on here, first I will address your actual question with the try-except block. I believe you want the except code to run when age value is out of range, but you need to actually generate an exception for the try statement to catch:
def calcBMI(minimum, maximum, val):
if val<minimum or val>maximum:
raise ValueError
# do stuff
try:
bmi = calcBMI(min_age, max_age, value)
except ValueError:
print("Error")
else:
print(bmi)
There is also a lot of bad form going on, you are using 18 separate near-identical lines to do something that only takes one! Those 18 lines where you fill up the processed list can be written as:
processed = [line.split(",") for line in lines]
Another thing is you run the same for-loop 3 times to populate age, height and weight lists. You could do this in one like this:
for line in processed:
age.append(line[2])
height.append(line[3])
weight.append(line[4])

How do I extract floating point values from .txt file to use for calculation in python?

count = 0
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
if line.startswith("X-DSPAM-Confidence:") :
print(line)
count = count + 1
print(count)
There is a file with 27 lines like X-DSPAM-Confidence : 0.xxxxx, I need to extract the numerical value from each of them to be used for calculations.
Try to use split(':'):
Code:
count = 0
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
if line.startswith("X-DSPAM-Confidence:") :
print(line)
value = line.split(':')[-1] # will split line into 'X-DSPAM-Confidence' and 'value'
# if you have ',' at the end of the line, simply do this:
value = value.strip(',')
value = float(value)
print(value)
count = count + 1
print(count)
As long as the format is exactly as you described it, you can use the code below:
float(line.split(':')[1])
If there's more variation in the text than what you described, you might need to try regex.
You can use str.rfind(':') to get the position of : and then do a string slice to get the value.
count = 0
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
if line.startswith("X-DSPAM-Confidence:") :
print(line)
value = line[line.rfind(':'):] # will take the last occurrence of : to slice the line
print(value)
count = count + 1
print(count)
fname = input("Enter file name: ")
fh = open(fname)
count = 0
pos = 0
ans = None
total = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") :
continue
else :
count = count + 1
pos = line.find(':')
ans = line[pos+1 : ]
total = total + float(ans)
avg = total/count
fname = input("Enter file name: ")
fh = open(fname)
val = 0
count = 0
for line in fh:
if line.startswith("X-DSPAM-Confidence:") :
count = count + 1
val=val + float(line[line.find('0'):])
elif not line.startswith("X-DSPAM-Confidence:") :
continue
print("Average spam confidence:",val/count)
fname = input("Enter file name:")
fh = open(fname)
count = 0
s=0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"):
continue
count = count+1
pos = line.find('0')
floatingP = float(line[pos:])
s += floatingP
print(s/count)

Opening a file for append error

I'm trying to open a file for appending, but I keep getting the "except" portion of my try/except block, meaning there is some sort of error with the code but I can't seem to find what exactly is wrong with it. It only happens when I try to open a new file like so:
results = open("results.txt", "a")
results.append(score3)
Here's my full code:
import statistics
# input
filename = input("Enter a class to grade: ")
try:
# open file name
open(filename+".txt", "r")
print("Succesfully opened", filename,".txt", sep='')
print("**** ANALYZING ****")
with open(filename+".txt", 'r') as f:
counter1 = 0
counter2 = 0
right = 0
answerkey = "B,A,D,D,C,B,D,A,C,C,D,B,A,B,A,C,B,D,A,C,A,A,B,D,D"
a = []
# validating files
for line in f:
if len(line.split(',')) !=26:
print("Invalid line of data: does not contain exactly 26 values:")
print(line)
counter2 += 1
counter1 -= 1
if line.split(",")[0][1:9].isdigit() != True:
print("Invalid line of data: wrong N#:")
print(line)
counter2 += 1
counter1 -= 1
if len(line.split(",")[0]) != 9:
print("Invalid line of data: wrong N#:")
print(line)
counter2 += 1
counter1 -= 1
counter1 += 1
#grading students
score = len(([x for x in zip(answerkey.split(","), line.split(",")[1:]) if x[0] != x[1]]))
score1 = 26 - score
score2 = score1 / 26
score3 = score2 * 100
a.append(score3)
# results file
results = open("results.txt", "a")
results.write(score3)
# in case of no errors
if counter2 == 0:
print("No errors found!")
# calculating
number = len(a)
sum1 = sum(a)
max1 = max(a)
min1 = min(a)
range1 = max1 - min1
av = sum1/number
# turn to int
av1 = int(av)
max2 = int(max1)
min2 = int(min1)
range2 = int(range1)
# median
sort1 = sorted(a)
number2 = number / 2
number2i = int(number2)
median = a[number2i]
median1 = int(median)
# mode
from statistics import mode
mode = mode(sort1)
imode = int(mode)
# printing
print ("**** REPORT ****")
print ("Total valid lines of data:", counter1)
print ("Total invalid lines of data:", counter2)
print ("Mean (average) score:", av1)
print ("Highest score:", max2)
print("Lowest score:", min2)
print("Range of scores:", range2)
print("Median Score:", median1)
print("Mode score(s):", imode)
results.close()
except:
print("File cannot be found.")
I don't think there is a method called append for writing into file. You can use the write or writelines method only to write. As you already opened the file with append permissions. It wont change the old data and will append the text to the file.
f=open('ccc.txt','a')
f.write('Hellloooo')
f.close()
Hope it helps.

Find Min and Max from Text File - Python

I need to find the minimum and max value from this list of data. I can get the maximum but the minimum. The text file has a lot of data so I decided to upload it here: https://www.dropbox.com/s/u5ov5zij9v5fumt/project05.data.txt?dl=0
Input
try:
file_name = input("Enter the name of an input file ")
input_file = open( file_name, "r" )
header=input_file.readline()
count=0
total=0
largest_num=0
smallest_num=0
michigan=""
for line in input_file:
output=float(line[67:71].rstrip())
total += output
count +=1
if largest_num<= output:
largest_num = output
if smallest_num >= output:
smallest_num = output
if line[0:17].rstrip() == "Michigan":
state=(line[0:17])
number=(line[67:75])
print("\nState with the smallest MMR vaccation rate:")
print(" with a rate of")
print("\n State with largest MMR vaccination rate:" )
print(" with a rate of")
print("\nThe calculated average vaccination rate is",round(total/count,1))
print("")
print("Michigan MMR vaccination rate is", number)
input_file.close()
except FileNotFoundError:
print("Error: file not found")
file_name = input("Enter the name of an input file ")
input_file = open( file_name, "r" )
List comprehensions are your friends.
numbers = [float(line[67:71].rstrip()) for line in input_file]
largest_num = max(numbers)
smallest_num = min(numbers)
total = sum(numbers)
count = len(numbers)

Categories

Resources