i have a input file having words "Olympics,Olympics,Olympics" when i try to count them and use function readlines() it count them as 1 rather than 3 !! what should i do !! this is my code

def input_files(file):
    sum=0
    #word=raw_input('enter the word you want to search\n')
    file=file.readlines()
    for lines in file:
        if word in lines:
            sum=sum+1
    print sum
word=raw_input('enter the word you want to search\n')
file =open("2.txt")
file2=open("3.txt")
input_files(file)
input_files(file2)

Recommended Answers

All 3 Replies

Replace line 7 with sum += lines.count(word). You can also remove line 6.

word=raw_input('enter the word you want to search\n')
for fn in '2.txt', '3.txt':
    with open(fn) as this_file:
        print fn, 'has', this_file.read().count(word), word

Dont use variable name as sum and file,these word are use by python.
So my_file is ok because it not used by python an give a NameError.

>>> sum
<built-in function sum>
>>> file
<type 'file'>
>>> my_file
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'my_file' is not defined

count() as used over is ok to use for a word as "Olympics".
But to count other word,it can act not as expected.
If i want to count word "hi" that occurred 1 time in variable s i get 4.

>>> s = 'hi is hirohito in japan,higher or lower'
>>> s.count('hi')
4

There are several way to solve this,split() and using collections.Counter can be one nice way.

>>> from collections import Counter
>>> s = 'hi is hirohito in japan,higher or lower'
>>> s = s.split()
>>> c = Counter(s)
>>> c['hi']
1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.