I am trying to get an average from a text file that uses a def function. I am trying to convert the list from the text file to int(). Instead of converting it gives me the error: " ValueError: invalid literal for int() with base 10: '5, 5, 6, 7' ". The "5, 5, 6, 7" is one that I made from the proper .txt file. Here is the code:
def getNumberList(filename):
with open(filename,'r') as f:
lyst = f.read().split('\n')
numberList = [int(num) for num in lyst]
return numberList
def getAverage(filename, func):
numbers = func(filename)
return sum(numbers)/len(numbers)
def main():
filename = input("Input the file name: ")
average = getAverage(filename, getNumberList)
print(average)
if __name__ == "__main__":
main()
You are splitting by line but you are not splitting by commas, so you are trying to convert 5,5,6,7 to an integer, which is impossible. You need to also split by commas after you split by line, and then combine them into one list, if you want to average all the numbers in the file. The following should work:
def getNumberList(filename):
with open(filename,'r') as f:
lines = f.readlines()
numberList = [int(num) for num in line.split(',') for line in lines]
return numberList
Looks like you might need to split each element with lyst using "," because right now it is trying to convert each line which has "1,2,3" as input.
So, change this and try.
def getNumberList(filename):
with open(filename,'r') as f:
lyst = []
temp = f.read().strip().split('\n')
for i in temp:
lyst += i.strip().split(',')
numberList = [int(num) for num in lyst]
return numberList
Related
# This program asks for an input and output file, and uses mult. and add.
# to combine files
def main():
print("This program creates a file of numbers from a")
print("file of numbers.")
infileName = input("What file are the numbers in? ")
outfileName = input("What file should the numbers go in? ")
infile = open(infileName, 'r')
outfile = open(outfileName, 'w')
for line in infile:
nums = line.split()
nums = float()
first = nums[0]
second = nums[-1]
newfirst = (first + second)
newsecond = (first * second)
print(newfirst, newsecond, file=outfile)
infile.close()
outfile.close()
print("Numbers have been written to", outfileName)
main()
the input txt file looks like this:
4.5 16.8
15 25
150 220.4
5.8 90
-1 -2
6.8 -2.3
this is what i have so far, I know everything is right other than the part where I split the input file. I just want to know how to convert the numbers in the input file to floats so i can add them and multiply them
You should replace this:
nums = line.split()
nums = float()
first = nums[0]
second = nums[-1]
with this:
nums = line.split()
first = float(nums[0])
second = float(nums[-1])
or this:
nums = [float(x) for x in line.split()]
first = nums[0]
second = nums[-1]
I'm pulling numbers from a file using regular expressions. When trying to print nums, it only gives me an empty list.
import re
fh = open('sample.txt')
for line in fh:
nums = re.findall('[0-9]+', line)
print(nums)
print(nums) prints an empty list. Why? I had to create a second for loop and append to a different list to get the numbers.
import re
fh = open('sample.txt')
numbers = []
for line in fh:
nums = re.findall('[0-9]+', line)
for num in nums:
num = int(num)
numbers.append(num)
print(numbers)
Why does print(numbers) return the numbers from the file, and print(nums) not?
sample.txt pulls data from: http://py4e-data.dr-chuck.net/regex_sum_483474.txt
Cause u print last match only...
Try with this:
import re
fh = open('sample.txt')
for line in fh:
nums = re.findall('[0-9]+', line)
print(nums)
I have a text file that contains these some words and a number written with a point in it. For example
hello!
54.123
Now I only want the number 54.123 to be extracted an converted so that the outcome is 54123
The code I tried is
import re
exp = re.compile(r'^[\+]?[0-9]')
my_list = []
with open('file.txt') as f:
lines = f.readlines()
for line in lines:
if re.match(exp, line.strip()):
my_list.append(int(line.strip()))
#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)
But this returns the error: ValueError: invalid literal for int() with base 10: '54.123'
Does anyone know a solution for this?
You can try to convert the current line to a float. In case the line does not contain a legit float number it returns a ValueError exception that you can catch and just pass. If no exception is thrown just split the line at the dot, join the 2 parts, convert to int and add to the array.
my_list = []
with open('file.txt') as f:
lines = f.readlines()
for line in lines:
try:
tmp = float(line)
num = int(''.join(line.split(".")))
my_list.append(num)
except ValueError:
pass
#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)
You can check if a given line is a string representing a number using the isdigit() function.
From what I can tell you need to just check if there is a number as isdigit() works on integers only (floats contain "." which isn't a number and it returns False).
For example:
def numCheck(string):
# Checks if the input string contains numbers
return any(i.isdigit() for i in string)
string = '54.123'
print(numCheck(string)) # True
string = 'hello'
print(numCheck(string)) # False
Note: if your data contains things like 123ab56 then this won't be good for you.
To convert 54.123 to 54123 you could use the replace(old, new) function.
For example:
string = 54.123
new_string = string.replace('.', '') # replace . with nothing
print(new_string) # 54123
This may help I am now getting numbers from the file I guess you were trying to use split in place of strip
import re
exp = re.compile(r'[0-9]')
my_list = []
with open('file.txt') as f:
lines = f.readlines()
for line in lines:
for numbers in line.split():
if re.match(exp, numbers):
my_list.append(numbers)
#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)
I just started learning Python a few weeks ago and I want to write a function which opens a file, counts and adds up the characters in each line and prints that those equal the total number of characters in the file.
For example, given a file test1.txt:
lineLengths('test1.txt')
The output should be:
15+20+23+24+0=82 (+0 optional)
This is what I have so far:
def lineLengths(filename):
f=open(filename)
lines=f.readlines()
f.close()
answer=[]
for aline in lines:
count=len(aline)
It does what I want it to do, but I don't know how to include all the of numbers added together when I have the function print.
If you only want to print the sum of the length of each line, you can do it like so:
def lineLengths(filename):
with open(filename) as f:
answer = []
for aline in f:
answer.append(len(aline))
print("%s = %s" %("+".join(str(c) for c in answer), sum(answer))
If you however also need to track lengths of all the individual lines, you can append the length for each line in your answer list by using the append method and then print the sum by using sum(answer)
Try this :
f=open(filename)
mylist = f.read().splitlines()
sum([len(i) for i in mylist])
Simple as this:
sum(map(len, open(filename)))
open(filename) returns an iterator that passes through each line, each of which is run through the len function, and the results are summed.
Once you read lines from file you can count sum using:
sum([len(aline) for aline in lines])
Separate you problem in function : a responsible by return total sum of lines and other to format sum of each line.
def read_file(file):
with open(file) as file:
lines = file.readlines()
return lines
def format_line_sum(lines):
lines_in_str = []
for line in lines:
lines_in_str.append(str(line)
return "+".join(str_lines))
def lines_length(file):
lines = read_file(file)
total_sum = 0
for line in lines:
total_sum += len(line)
return format_lines_sum(lines) + "=" + total_sum
And to use:
print(lines_length('file1.txt'))
Assuming your output is literal, something like this should work.
You can use python sum() function when you figure out how to add numbers to the list
def lineLengths(filename):
with open(filename) as f:
line_lengths = [len(l.rstrip()) for l in f]
summ = '+'.join(map(str, line_lengths)) # can only join strings
return sum(line_lengths), summ
total_chars, summ = lineLengths(filename)
print("{} = {}".format(summ, total_chars))
This should have the output you want : x+y+z=a
def lineLengths(filename):
count=[]
with open(filename) as f: #this is an easier way to open/close a file
for line in f:
count.append(len(line))
print('+'.join(str(x) for x in count) + "=" + str(sum(count))
def make_number_list(a_file):
number_list= []
for line_str in a_file:
line_list = line_str.split()
for number in line_list:
if number != " ":
number_list.append(number)
return number_list
opened_file = open(input("Name of input file: "))
a_file_list = make_number_list(opened_file)
print(a_file_list)
print("Length: ", len(a_file_list))
I am trying to read (eventually) 1000 integer values from a file into a list.. then find their max, min and i th value. However, this is not working to read the list (I'm just using a test list which is a file in TextEdit and is a bunch of random numbers separated by a single white space). Any suggestions?
# assumes Python 3.x
def read_nums(fname):
with open(fname) as inf:
return [int(i) for i in inf.read().split()]
def main():
fname = input("Name of input file: ")
nums = read_nums(fname)
print("Read {} numbers".format(len(nums)))
if __name__=="__main__":
main()
I am not sure how the numbers are present in your input file. Nonetheless, there are a few changes you could do to your code:
Move the return statement outside the loop.
A better way of checking if number exists would be:
if number.isdigit():
Which gives you:
def make_number_list(a_file):
number_list= []
for line_str in a_file:
line_list = line_str.split()
for number in line_list:
if number.isdigit():
number_list.append(number)
return number_list