2016-09-10 112 views
2

试图在python中构建一个搜索功能,该功能从用户处获取输入值/字符串,搜索外部文件,然后返回总计数)该文件中的请求值。Python:在文件中搜索特定字符串并输出总字符串数

if user_search_method == 1: 
with open("file.txt", 'r') as searchfile: 
    for word in searchfile: 
     word = word.lower() 
     total = 0 
     if user_search_value in word.split(): 
      total += word.count(user_search_value) 
      print total 

当我运行这个,虽然我得到一个行由行计数显示,而不是总和。当我合计这些线时,它们总是比实际少1个数。

+4

你需要你的'print'声明在同一“for”语句的缩进级别。我通常也希望调用readlines()。你的意思是说最后的计数是一个短数,还是计数的行数? – Andrew

回答

2

您在每次迭代中打印total时,必须将其从for循环中取出。你也可以做这个工作更Python,使用一台发电机的表达:

if user_search_method == 1: 
    with open("file.txt") as searchfile: 
     total = sum(line.lower().split().count(user_search_value) for line in searchfile) 
    print total 
+0

不会破坏发电机 - 不止一条线路 - 更清晰吗? – boardrider

+0

@boardrider没有,因为它只有一个循环。 – Kasramvd

+0

考虑到OP的Python级别,我不确定他们能否轻松掌握复杂生成器的含义。 似乎Python中的几行支持我的断言。 – boardrider

-1
if user_search_method == 1:  
    total = 0  
    with open('file.txt') as f: 
    for line in f: 
     total += line.casefold().split().count(user_search_value.casefold()) 
    print(total) 

这是你想要的大概是什么做的。

0

感觉就像有可能是一些从你的问题不见了,但我会努力让你在那里,似乎你想要去的......

user_search_value = 'test'      # adding this for completeness of 
               # this example 
if user_search_method == 1: 
    with open("file.txt", 'r') as searchfile: 
     total = 0 
     for word in searchfile: 
      words = word.lower().split()  # breaking the words out, upfront, seems 
               # more efficient 

      if user_search_value in words: 
       total += words.count(user_search_value) 
     print total       # the print total statement should be outside the for loop