简体   繁体   中英

How to find on which line a specific word is. [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

PS: I want to fine the index number of the line, and not print the whole line

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, eg "dog" will be found in "dogs". To have full words (ie separated by spaces) you need to additionally split lines into words.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM