Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find on which line a specific word is. [python]

Tags:

python

I am trying to create a program, that counts the line, counts a specific word, and then tells you on which line it is. Now I did the first two, however I am not sure how to find on which line the word is. any suggestions ? this is my code currently:

 name = input('Enter name of the text file: ')+'.txt'

file = open(name,'r')

myDict = {}
linenum = 0

for line in file:
    line = line.strip()
    line = line.lower()
    line = line.split()
    linenum += 1

print(linenum-1)

count = 0
word = input('enter the word you want us to count, and will tell you on which line')
#find occurence of a word
with open(name, 'r') as inF:
    for line in inF:
        if word in line:
            count += 1

#find on which line it is

P.S: I want to fine the index number of the line, and not print the whole line

like image 592
matrixCode Avatar asked Feb 20 '15 02:02

matrixCode


Video Answer


1 Answers

Your program can be simplified as follows:

# read the file into a list of lines
with open('data.csv','r') as f:
    lines = f.read().split("\n")


print("Number of lines is {}".format(len(lines)))

word = 'someword' # dummy word. you take it from input

# iterate over lines, and print out line numbers which contain
# the word of interest.
for i,line in enumerate(lines):
    if word in line: # or word in line.split() to search for full words
        print("Word \"{}\" found in line {}".format(word, i+1))

For the following example text file:

DATE,OPTION,SELL,BUY,DEAL
2015-01-01 11:00:01, blah1,0,1,open
2015-01-01 11:00:01, blah2,0,1,open
2015-01-01 11:00:01, blah3,0,1,open
2015-01-01 11:00:02, blah1,0,1,open
2015-01-01 11:00:02, blah2,0,1,someword
2015-01-01 11:00:02, blah3,0,1,open

The program results in:

Number of lines is 7
Word "someword" found in line 6

Please note that this does not take into consideration an example where you have substrings, e.g. "dog" will be found in "dogs". To have full words (i.e. separated by spaces) you need to additionally split lines into words.

like image 52
Marcin Avatar answered Sep 24 '22 02:09

Marcin