Reputation: 357
I want to find number of lines and words in a file. My input file "testfile.txt' has 6 lines and 23 words. For finding number of words I am using map() function instead of the for loop. When I executed this code it shows the memory location of the object instead of "23": Number of words =
What am I doing wrong here?
def wordcount(l):
global numwords
words = l.split()
numwords += len(words)
f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)
numwords=0
numwords = map(wordcount, lines)
print ('Number of words =', numwords)
Upvotes: 1
Views: 2792
Reputation: 11
Read paragraphs to lines and ...
print 'Num of words =', reduce(lambda x,y: x+y ,[len(line.split()) for line in lines])
Upvotes: 1
Reputation: 435
Here you go, map either returns a list or iterator, so this modification will work in either case. (python2 vs python3)
def wordcount(l):
global numwords
words = l.split()
numwords += len(words)
f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)
numwords=0
numwords = map(wordcount, lines)
print ('Number of words =', len(list(numwords)))
Upvotes: 0
Reputation: 131647
In Python 3, map
is an iterator: (akin: itertools.imap
)
class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
While in Python 2:
map(...)
map(function, sequence[, sequence, ...]) -> list
It returns a list
by default.
So in your case, you need to do:
numwords = list(map(wordcount, lines))
There are other problems also with your code, but others have pointed that out well enough.
Upvotes: 2
Reputation: 41030
You should avoid to use a global variable like 'numwords'. You have to return numwords in your wordcount() function.
This code works :
def wordcount(l):
numwords = 0
words = l.split()
numwords += len(words)
return numwords
f = open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print('Number of lines =', numlines)
numwords = 0
numwords = map(wordcount, lines)
print ('Number of words =', numwords)
My testfile.txt contains :
Hello world
my name is
james bond
Ouput :
('Number of lines =', 3)
('Number of words =', [2, 3, 2])
Upvotes: 1
Reputation: 74645
after:
numwords = map(wordcount, lines)
numwords
is a list of None
the same length as lines
as wordcount
returns None
for line in lines:
words = line.split()
numwords += len(words)
would be better and more pythonic
Upvotes: 2
Reputation: 7682
function wordcount doesn't return anything, write return numwords
Now your function calcualates numwords and then return None by default, and you erase this global variable
Upvotes: 0