Reputation: 589
The Program I need help is written below
def countHits(file):
f2 = open(file,'rU')
l2 = f2.readlines()
f2.close()
user_input = raw_input("Enter the URL that you wish to chck fr the nmber of Hits")
print "The number of HITS for the given STRING/URL is : %s"%(l2.count(user_input))
def main():
strin = raw_input("Enter the file name\n")
countHits(strin)
if __name__ == '__main__':
main()
The file given as input contains list of urls (mentioned below):
/RLSsdTfswds/images//innercontainer-collapse.gif
/RL/css/default.css
/RLSTsdsdRdsdU/scripts/highslide/graphics/outlines/rounded-white.png
/RLSsdsdTsdsRsddU/scripts/highslide/graphics/zoomout.cur
/RLS/css/highslide/highslide/graphics/loader.white.gif
/RL/css/default.css
/RLST/rws/scripts/processschScript.js
/RLSR/scripts/NumberFormat.js
/RL/css/default.css
My query is that when I try to find url "/RL/css/default.css", the program doesn't gives me the count. Help me where I'm making a mistake ?
Upvotes: 1
Views: 94
Reputation:
Try to remove trailing whitespace from the input.
print "The number of HITS for the given STRING/URL is : %s" % (
l2.count(user_input.strip())
)
Upvotes: 0
Reputation: 1093
Using List Comprehension is faster than lambda function.
def countHits(file):
f2 = open(file,'rU')
l2 = f2.readlines()
f2.close()
user_input = raw_input(
"Enter the URL that you wish to chck fr the nmber of Hits"
)
lst = [(s.strip()) for s in l2]
print "The number of HITS for the given STRING/URL is : %s" % (
lst.count(user_input.strip())
)
def main():
strin = raw_input("Enter the file name\n")
countHits(strin)
if __name__ == '__main__':
main()
Upvotes: 0
Reputation: 195
The following lines can be found in the documentation:
f.readline() reads a single line from the file;
a newline character (\n) is left at the end of the string,
and is only omitted on the last line of the file if the file doesn’t end in a newline.
This makes the return value unambiguous;
if f.readline() returns an empty string,
the end of the file has been reached,
while a blank line is represented by '\n',
a string containing only a single newline.
Though, you need to "sanitize" every line which is being read with file.readlines()
,
like this for instance:
with open(file, 'r') as f :
data = [x.strip() for x in f.readlines()]
And data
will contain the list of lines, without tabs, spaces or newlines.
Upvotes: 2
Reputation: 2351
Possible solution:
def countHits(file):
f2 = open(file,'rU')
l2 = f2.readlines()
f2.close()
l2 = [l.strip() for l in l2]
user_input = raw_input(
"Enter the URL that you wish to chck fr the nmber of Hits"
)
print "The number of HITS for the given STRING/URL is : %s"% (
l2.count(user_input)
)
I guess this will work faster.
def countHits(file):
f2 = open(file,'rU')
l2 = f2.readlines()
f2.close()
l2 = map(lambda x: x.strip(), l2)
user_input = raw_input(
"Enter the URL that you wish to chck fr the nmber of Hits"
)
print "The number of HITS for the given STRING/URL is : %s"% (
l2.count(user_input)
)
Upvotes: 1