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))
Related
So I have this problem I need to solve. I have a file that goes something like:
11-08-2012;1485;10184;7,53;31;706;227;29;6;1102
12-08-2012;2531;10272;7,59;25;695;222;26;22;1234
13-08-2012;1800;13418;8,66;46;714;203;50;6;0757
14-08-2012;2009;11237;9,43;81;655;246;49;7;1783
And I should be able to read the "1485" and then the "2531" part and then the "1800" part and go all the way to the end of the file and finally sum them up. How do I do that? I wrote under this text how I tried to approach this problem with while. But I seem to be lost with this one. Anyone can help?
while True:
f.seek(12)
text=f.read(4)
text=f.readline()
if(text==""):
break
return text
There are number of ways to do this, with numpy, pandas, simple coroutines and so on. I am adding the one closest to your approach.
total = 0
with open('exmplefile.txt','r') as f:
for line in f:
elements = line.split(';')
num_of_interest = int(elements[1])
# you can add a print if you want
total += num_of_interest
print(total)
This solution is by getting the first and second index of a common term, in this case ;.
with open(filename,'r') as file:
file_list = file.readlines()
sum = 0
for line in file_list:
loc = line.find(';')
first_loc = loc + 1
last_loc = loc +line[loc+1:].find(';')+1
sum = sum + int(line[first_loc:last_loc])
print(sum)
Try this
mylist = []
for string in file:
mynum = string.split(';')[1]
mylist.append(mynum)
sum([int(i) for i in mylist])
This solution caters for when the 4 digit is not the second item in the array
with open("path/to/file") as f:
f1 = f.readlines()
sum = 0
for line in f1:
lineInArray = line.split(';')
for digit in lineInArray:
if len(digit.strip()) == 4 and digit.strip().isnumeric():
sum += int(digit)
I'd like to create a program in python 3 to find how many time a specific words appears in txt files and then to built an excel tabel with these values.
I made this function but at the end when I recall the function and put the input, the progam doesn't work. Appearing this sentence: unindent does not match any outer indentation level
def wordcount(filename, listwords):
try:
file = open( filename, "r")
read = file.readlines()
file.close()
for x in listwords:
y = x.lower()
counter = 0
for z in read:
line = z.split()
for ss in line:
l = ss.lower()
if y == l:
counter += 1
print(y , counter)
Now I try to recall the function with a txt file and the word to find
wordcount("aaa.txt" , 'word' )
Like output I'd like to watch
word 4
thanks to everybody !
Here is an example you can use to find the number of time a specific word is in a text file;
def searching(filename,word):
counter = 0
with open(filename) as f:
for line in f:
if word in line:
print(word)
counter += 1
return counter
x = searching("filename","wordtofind")
print(x)
The output will be the word you try to find and the number of time it occur.
As short as possible:
def wordcount(filename, listwords):
with open(filename) as file_object:
file_text = file_object.read()
return {word: file_text.count(word) for word in listwords}
for word, count in wordcount('aaa.txt', ['a', 'list', 'of', 'words']).items():
print("Count of {}: {}".format(word, count))
Getting back to mij's comment about passing listwofwords as an actual list: If you pass a string to code that expects a list, python will interpret the string as a list of characters, which can be confusing if this behaviour is unfamiliar.
Suppose I have a text file containing this, where the number on the left says how many of the characters of the right should be there:
2 a
1 *
3 $
How would I get this output in the fastest time?
aa*$$$
This is my code, but has N^2 complexity:
f = open('a.txt')
for item in f:
item2=item.split()
num = int(item2[0])
for i in range(num):
line+=item2[1]
print(line)
f.close()
KISS
with open('file.txt') as f:
for line in f:
count, char = line.strip().split(' ')
print char * int(count),
Just print immediately:
for item in open('a.txt'):
num, char = item.strip().split()
print(int(num) * char, end='')
print() # Newline
You can multiply strings to repeat them in Python:
"foo" * 3 gives you foofoofoo.
line = []
with open("a.txt") as f:
for line in f:
n, c = line.rstrip().split(" ")
line.append(c * int(n))
print("".join(line))
You can print directly but the code above lets you get the output you want in a string if you care about that.
Using a list then joining is more efficient than using += on a string because strings are immutable in Python. This means that a new string must be created for each +=. Of course printing immediately avoids this issue.
You can try like this,
f = open('a.txt')
print ''.join(int(item.split()[0]) * item.split()[1] for item in f.readlines())
Your code is actually O(sum(n_i)) where n_i is the number in the row i. You can't do any better and none of the solutions in the other answers do, even if they might be faster than yours.
I need to make a program that generates 10 random integers between 10 and 90 and calls two separate functions to perform separate actions. The first one (playlist) simply needs to print them all on one line without spaces, which was easy. The second one (savelist) is giving me problems. I need to write every number in the list nums to angles.txt with each number on a separate line in order. No matter what I try I can't get them on separate lines and it appears as one string on a single line. What am I missing?
import random
def main():
nums = []
# Creates empty list 'nums'
for n in range(10):
number = random.randint(10, 90)
nums.append(number)
# Adds 10 random integers to list
playlist(nums)
savelist(nums)
def playlist(numb):
index = 0
while index < len(numb):
print(numb[index], end=' ')
index += 1
def savelist(number):
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
myfile.write(str(number) + '\n')
myfile.close()
main()
In savelist(), you need to loop through the list:
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
for e in number:
myfile.write(str(e))
myfile.close()
When you send "nums" to savelist(), you are sending a list. If you just try to write "numbers" to the file, it's going to write the whole list. So, by looping through each element in the list, you can write each line to the file.
To write a list to a file you need to iterate over each element of the list and write it individually, with the attached newline. For example:
def savelist(number):
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
for n in number:
myfile.write(str(number) + '\n')
myfile.close()
You could also generate a single string by joining your list with newlines, and then write that to the file. For example:
myfile.write('\n'.join([str(n) for n in number])
Finally, you may want to consider using a context manager on the file open, to ensure that the file is closed whatever happens. For example:
def savelist(nums):
# Creates numbers.txt file
nums.sort()
with open('angles.txt', 'w') as myfile:
myfile.write('\n'.join([str(n) for n in nums])
Note that I also changed the variable name to nums rather than number ('number' is slightly confusing, since the list contains >1 number!).
Try this code out: You are writing an array as a whole to the file, and therefore are seeing only one line.
def main():
nums = [] # Creates empty list 'nums'
for n in range(10):
number = random.randint(10, 90)
nums.append(number)
# Adds 10 random integers to list
playlist(nums)
savelist(nums)
def playlist(numb):
index = 0
while index < len(numb):
print(numb[index], end=' ')
index += 1
def savelist(number):
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
for element in number:
myfile.write(str(element) + '\n')
myfile.close()
main()
#tomlester already stated that you need to loop through the elements in number. Another way to do this is.
def savelist(number):
number.sort()
with open('angles.txt', 'w') as myfile:
myfile.write('\n'.join(map(str, number)))
Here's how I would do it:
from random import randint
def rand_lst(lo, hi, how_many):
return [randint(lo, hi) for _ in range(how_many)]
def print_lst(nums):
print(''.join(str(num) for num in nums))
def save_lst(nums, fname):
with open(fname, "w") as outf:
outf.write('\n'.join(str(num) for num in sorted(nums)))
def main():
nums = rand_lst(10, 90, 10)
print_lst(nums)
save_lst(nums, "angles.txt")
if __name__ == "__main__":
main()
I am both new to programming and python. I need to read a list in a file, use a while-loop or for-loop to alphabetize that list and then write the alphabetized list to a second file. The file is not sorting and it is not writing to the file. Any insight or constructive criticism is welcome.
unsorted_list = open("unsorted_list.txt", "r") #open file congaing list
sorted_list = open ("sorted_list.txt", "w") #open file writing to
usfl = [unsorted_fruits.read()] #create variable to work with list
def insertion_sort(list): #this function has sorted other list
for index in range(1, len(list)):
value = list[index]
i = index - 1
while i >= 0:
if value < list[i]:
list[i+1] = list[i]
list[i] = value
i = i - 1
else:
break
insertion_sort(usfl) #calling the function to sort
print usfl #print list to show its sorted
sfl = usfl
sorted_furits.write(list(sfl)) #write the sorted list to the file
unsorted_fruits.close()
sorted_fruits.close()
exit()
If insertion_sort worked before, I guess it works now, too. The problem is that usfl contains only one element, the content of the file.
If you have a fruit on each line, you can use this to populate your list:
usfl = [line.rstrip () for line in unsorted_fruits]
or if it is a comma separated list, you can use:
usfl = unsorted_fruits.read ().split (',')
Your problem seems to be the way you're handling files.
Try something along the lines of:
input_file = open("unsorted_list.txt", "r")
output_file = open("sorted_list.txt", "w")
#Sorting function
list_of_lines = list(input_file) #Transform your file into a
#list of strings of lines.
sort(list_of_lines)
long_string = "".join(list_of_lines) #Turn your now sorted list
#(e.g. ["cat\n", "dog\n", "ferret\n"])
#into one long string
#(e.g. "cat\ndog\nferret\n").
output_file.write(long_string)
input_file.close()
output_file.close()
exit()
Let me begin by saying thank you to all the answers. Using the answer here to guide me in searching and tinkering I have produced code that works as required.
infile = open("unsorted_fruits.txt", "r")
outfile = open("sorted_fruits.txt", "w")
all_lines = infile.readlines()
for line in all_lines:
print line,
def insertion_sort(list):
for index in range(1, len(list)):
value = list[index]
i = index - 1
while i >= 0:
if value < list[i]:
list[i+1] = list[i]
list[i] = value
i = i - 1
else:
break
insertion_sort(all_lines)
all_sorted = str(all_lines)
print all_sorted
outfile.write(all_sorted)
print "\n"
infile.close()
outfile.close()
exit()