2016-10-15 4 views
0

私は、テキストファイルを検索し、ユーザー定義の単語が表示される回数を数えるためにpythonを使用しようとしています。しかし、ユニークな単語がファイルに現れる回数の合計を取得する代わりに私のコードを実行すると、そのファイル内のその単語を含む数行がカウントされます。Pythonの検索テキストファイルと指定された文字列のカウントの出現

例:「bob」という単語がテキストファイルに56回存在し、合計63行のテキストのうち19行に表示されます。私のコードを実行すると、コンソールは '19'を表示します。

私は分割方法で何か別のことをする必要があると思いますか?私はPython 2.7.10を実行しています。私はと遊んだ後、上記のコメントで述べたように

user_search_value = raw_input("Enter the value or string to search for: ") 

count = 0  

with open(file.txt, 'r') as f: 
    for line in f.readlines(): 
     words = line.lower().split() 
     for word in words: 
      if word == user_search_value: 
       count += 1 
print count 
+0

は、回答いただきありがとうございます...しかし、私はあなたの提案に差し込まれたとき、私は同じです私のコードが生産したものを数えます。私はこれをしばらく試してみて、やっとそれを理解しました。 – Ryan

答えて

0

一つの方法は、言葉以上のループになります私がそれを理解している間、これは(長い)ためです。私のコードは以下の通りです。

#read file 
f = open(filename, "r") 
lines = f.readlines() 
f.close() 
#looking for patterns 
for line in lines: 
    line = line.strip().lower().split() 
    for words in line: 
     if words.find(user_search_value.lower()) != -1: 
      count += 1 
print("\nYour search value of '%s' appears %s times in this file" % (user_search_value, count)) 
0

:あなたが行を分割し、それぞれの一致する単語のためのcountをインクリメントした後、これを行うには

user_search_value = raw_input("Enter the value or string to search for: ") 

count = 0  

with open(file.txt, 'r') as f: 
    for word in f.readlines(): 
     words = word.lower().split() 
     if user_search_value in words: 
      count += 1 
    print count 
0

「指定された文字列は」ここに、スペースでフレーズの場合は、動作するものである:

#!/usr/bin/python 

import sys 
import os 

def count_words_in_file(filepath, words, action=None): 
    with open(filepath) as f: 
     data = f.read() 
     for key,val in words.items(): 
      print "key is " + key + "\n" 
      ct = data.count(key) 
      words[key] = ct 
     if action: 
      action(filepath, words) 


def print_summary(filepath, words): 
    print(filepath) 
    for key,val in sorted(words.items()): 
     print('{0}:\t{1}'.format(
      key, 
      val)) 


filepath = sys.argv[1] 
keys = ["Hello how are you", 
"Another phrase with spaces", 
"A phrase with spaces and some punctuation."] 
words = dict.fromkeys(keys,0) 

count_words_in_file(filepath, words, action=print_summary) 
関連する問題