2016-09-10 15 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()'の呼び出しも期待しています。最終的なカウントが1つ短いか、カウントしたライン数ですか? – Andrew

答えて

2

を各繰り返しで印刷していますが、ループをforループから外す必要があります。また、あなたは1つのジェネレータ式を使用して、より多くのニシキヘビこの仕事を行うことができます。これは、あなたがやって欲しかった、おそらく何である

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 Noループは1つだけです。 – Kasramvd

+0

明らかなPythonレベルのOPがあれば、複雑なジェネレータの意味を容易に把握できるかどうかはわかりません。 The Zen of 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 
関連する問題