列表计数方法问题

时间:2014-11-07 13:00:49

标签: python list

我需要帮助的计划如下:

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()

作为输入提供的文件包含网址列表(如下所述):

/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

我的疑问是,当我尝试查找网址“/RL/css/default.css”时,该程序并未向我提供计数。帮助我在哪里弄错了?

4 个答案:

答案 0 :(得分:2)

documentation中可以找到以下几行:

  

f.readline()从文件中读取一行;
  换行符(\ n)留在字符串的末尾,
  如果文件没有以换行符结尾,则仅在文件的最后一行中省略   这使得返回值明确;
  如果f.readline()返回一个空字符串,
  已达到文件末尾,
  而空白行由' \ n',
表示   一个只包含一个换行符的字符串。

但是,你需要"消毒"用file.readlines()读取的每一行,
比如这样:

with open(file, 'r') as f :
    data = [x.strip() for x in f.readlines()]

data将包含行列表,没有制表符,空格或换行符。

答案 1 :(得分:1)

可能的解决方案:

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)
    )

我想这会更快。

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)
    )

答案 2 :(得分:0)

尝试从输入中删除尾随空格。

print "The number of HITS for the given STRING/URL is : %s" % (
   l2.count(user_input.strip())
)

答案 3 :(得分:0)

使用List Comprehension比lambda函数更快。

 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()