Python Search Text File And Count Occurrences Of A Specified String
I am attempting to use python to search a text file and count the number of times a user defined word appears. But when I run my code below instead of getting a sum of the number o
Solution 1:
One way to do this would be to loop over the words after you split the line and increment count
for each matching word:
user_search_value = raw_input("Enter the value or string to search for: ")
count = 0withopen(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
Solution 2:
As I mentioned in the comment above, after playing with this for a (long) while I figured it out. My code is below.
#read file
f = open(filename, "r")
lines = f.readlines()
f.close()
#looking for patterns
for line inlines:
line = line.strip().lower().split()
for words in line:
if words.find(user_search_value.lower()) != -1:
count += 1print("\nYour search value of '%s' appears %s times in this file" % (user_search_value, count))
Solution 3:
If the "specified string" is a phrase with spaces, here is one that works:
#!/usr/bin/pythonimport sys
import os
defcount_words_in_file(filepath, words, action=None):
withopen(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)
defprint_summary(filepath, words):
print(filepath)
for key,val insorted(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)
Post a Comment for "Python Search Text File And Count Occurrences Of A Specified String"