Value Error : need more than 1 value to unpack - python

I am working on a word count program.
#!/usr/bin/env python
import sys
# maps words to their counts
word2count = {}
# input comes from STDIN
for line in sys.stdin:
line = line.strip()
word, count = line.split('\t', 1)
try:
count = int(count)
except ValueError:
continue
try:
word2count[word] = word2count[word]+count
except:
word2count[word] = count
for word in word2count.keys():
print '%s\t%s'% ( word, word2count[word] )
Error for this code:
word, count = line.split('\t', 1)
ValueError : need more than 1 value to unpack

Moving word, count = line.split('\t', 1) in the try-except should work:
for line in sys.stdin:
line = line.strip()
try:
word, count = line.split('\t', 1)
count = int(count)
except ValueError:
continue
This would skip all the lines that do not have a number at the beginning of the line that is separated with a tab from the rest of the line.

Related

Map Reduce program to calculate the average and count

I am trying to calculate the taxi and its trip using map reduce python program.
In Map program I have written the following code where it will assign each row a key.
import sys
for line in sys.stdin:
line = line.strip()
words = line.split(",")
trip = words[0]
km = words[1]
print('%s\t%s\t%s' % (trip, km, "1"))
Next while in reducer below is the program.
#!/usr/bin/env python3
import sys
current_trip = None
current_km = 0
current_count = 0
trip = None
gender = None
for line in sys.stdin:
line = line.strip()
trip,gender,count = line.split(",")
try:
count = int(count)
except ValueError:
continue
if current_trip == trip:
current_km = (km + current_km)
current_count += count
print('%s\t%s' % (current_trip,current_count, {current_km/current_count}))
current_trip = trip
current_count = count
current_km = 0
else:
if current_trip == trip:
current_count += count
print('%s\t%s' % (current_trip, current_count,km))
Here I am getting the error saying
Traceback (most recent call last):
File "reducer.py", line 23, in <module>
print('%s\t%s\t%s' % (current_trip, current_count, {current_km / current_count}))
ZeroDivisionError: division by zero
and I am not able to debug properly because if I include the print statement it is not printing in output.
Can someone please help
If the first line contains a count 0, or you have negative counts and at some point the current_count is 0, you will get this error. Try to add a condition before your print method to debug the problem:
if current_count != 0:
print('%s\t%s' % (current_trip,current_count, {current_km/current_count}))
else:
print(f"error: the current_count is 0 and the count is {count}")

reading and deleting lines in python

I am trying to read all the lines in a specific file, and it prints the number of the line as an index.
What I am trying to do is to delete the line by inputting the number of the line by the user.
As far as it is now, it prints all the lines with the number of that line, but when I enter the number of the line to be deleted, it's not deleted.
This is the code of the delete function:
def deleteorders ():
index = 0
fh = open ('orders.txt', 'r')
lines = fh.readlines()
for line in lines:
lines = fh.readlines()
index = index+1
print (str(index) + ' ' + line)
try:
indexinp = int(input('Enter the number of the order to be deleted, or "B" to go back: '))
if indexinp == 'B':
return
else:
del line[indexinp]
print (line)
fh = open ('orders.txt', 'w')
fh.writelines(line)
fh.close()
except:
print ('The entered number is not in the range')
return
This should work (you'll need to add the error handling back in):
lines = enumerate(open('orders.txt'))
for i, line in lines:
print i, line
i = int(input(">"))
open('orders.txt', 'w').write(''.join((v for k, v in lines if k != i)))

Counting number of words and letters from txt. file

I am beginner in programming and currently facing issue with simple task. I would need to print words, calculate number of particular words and also number of letters from txt.file. I would appreciate if someone could help me with this:
def main():
file_name = input("Input file. \n")
sum_of_letters = 0
number_words = 0
try:
words = open(file_name, "r")
print("File", file_name ,"includes the following words:")
for line in words:
line = line.rstrip()
words= line.split()
for i in words:
print(i)
sum_of_letters += len(i)
number_words += 1
print("---------------------------------------")
print("Number of words",number_words ,"ja", sum_of_letters, "kirjainta.")
close.words()
except OSError:
print("Error observed")
Your code is almost correct but you're using words to refer to both the file as well as the words in a single line. I've updated the code below to use different variables:
def main():
file_name = input("Input file. \n")
sum_of_letters = 0
number_words = 0
try:
words = open(file_name, "r")
print("File", file_name ,"includes the following words:")
for line in words:
line = line.rstrip()
words_in_line = line.split()
for i in words_in_line:
print(i)
sum_of_letters += len(i)
number_words += 1
print("---------------------------------------")
print("Number of words",number_words ,"ja", sum_of_letters, "kirjainta.")
words.close()
except OSError:
print("Error observed")

list index out of range sorting highest to lowest

file = open("1.txt")
classj = (file.readlines())
s = []
for line in sorted(classj):
classj = (line.rstrip())
classa = (classj.split("-"))#sort
score = int(classa[1])
name = (classa[0])
s.append( (name,score) )
s.sort(reverse=True, key=lambda x:x[1])
for x in s:
print(x[0],"-",x[1])
I have got the content of a text file in which I have scores in which I need to sort from high to low but it originally printed only the scores but now I get the message list index out of range
Your file has some lines, with no - in it. Perhaps an empty line?
You can ignore empty lines, or you can ignore lines with no '-':
with open("1.txt") as inp:
s = []
for line in inp:
line = line.strip()
if not line:
continue
try:
name, score = line.split('-')
except ValueError:
print("Warning! Ignore line: %s" % line)
else:
s.append(name, int(score))
s.sort(reverse=True, key=lambda x:x[1])
for name, score in s:
print(name,"-",score)

#list index out of range

def isexact(pat):
for c in pat.upper():
if c not in 'ATGC':
return 0
return 1
def print_matches(ofh, enz, matches):
if matches:
print >>ofh, "Enzyme %s matches at:" % enz,
for m in matches:
print >>ofh, m,
print >>ofh
else:
print >>ofh, "No match found for enzyme %s." % enz
def get_site_only(pat):
newpat = ""
for c in pat:
if c.isalpha():
newpat += c
return newpat
def findpos(seq, pat):
matches = []
current_match = seq.find(pat)
while current_match != -1:
matches.append(current_match)
current_match =seq.find(pat, current_match+1)
return matches
seq = ""
ifh = open("C:\Python27\\link_cutzymes.txt",'r')
ofh = open("C:\Python27\\re-en-output.txt", "w")
line = ifh.readline()
while line:
fields = line.split()
name = fields[0]
pat = get_site_only(fields[2])
if isexact(pat):
print_matches(ofh, name, findpos(seq, pat))
line = ifh.readline()
else:
line = ifh.readline()
ofh.close()
ifh.close()
it is showing list index error can help me
Traceback (most recent call last): File
"C:/Users/ram/Desktop/rest_enz7.py", line 55, in
name = fields[0] IndexError: list index out of range
name = fields[0] - you probably are reading an empty line, splitting it, and accessing it at index 0, which is out of range for an empty list..
you can make sure your file contains only lines of your format, check for empty lines in the code, or use try and except to name a few options.
while reading the data from file,if data is not exist to split,it will not convert into list. I can see in your code name = fields[0] is causing error.
At that time please use try and except in your code.
you can rewrite the code as :
try:
fields = line.split()
name = fields[0]
except:
pass
What a string[x] does is get the xth letter of the list. This means that if there is no object in the xth position then you get an error.
So if name = fields[0] returns an error then fieldsmust be an empty list (It would look like this: []) because there is no first object (Python counts from zero so letter 0 is letter 1, letter 1 is letter 2 and so on). You can fix this with a try: and except: like so:
try:
name = fields[0]
except:
name = '' #Or whatever code you want to run if it fails
In the place of name = fields[0]

Categories