1

How do you get your function to find the lines in the text file where the word occurs and print the corresponding line numbers?

I had to open a text file with the paragraph and then am supposed to search the paragraph for certain words and then print the specific line numbers for the words.

Here is what I have so far.

def index (filepath, keywords):

    file = open(filepath)
    files_lines = [line for line in file]
    counter = 0
    for line in files_lines:
        counter += 1
        if line.find(keywords) >= 0:
            print(keywords, counter)
    counter = 0

This is how the output should be

    >>index('file.txt',['network', 'device', 'local'])

network    9

device     4

local      11

Note: Network, Device and local are the words im trying to search within the file and 9, 4, 11 are the line numbers on which these words occur.

I am getting an error that cannot convert list into str implicitly. Any help would be really appreciated. Thanks.

user3609260
  • 21
  • 2
  • 4

3 Answers3

2
if line.find(keywords) >= 0: 

is wrong. you need to find out if any element of keywords is contained in line. like this

if any(line.find(kw) > 0 for kw in keywords):

BTW, the lines

files_lines = [line for line in file]
counter = 0

are not very pythonic, better like this:

def index (filepath, keywords):
    with open(filepath) as f:
        for counter, line in enumerate(f, start = 1):
            if line.find(keywords) >= 0:
               print(keywords, counter)

Acknowledgement: Thanks to Lukas Graf for showing me it's necessary to set the start parameter in enumerate

gefei
  • 18,922
  • 9
  • 50
  • 67
  • 1
    That won't result in the OP's example output though, and line numbers will be off by one. – Lukas Graf Sep 14 '14 at 19:43
  • You should use 'in' instead of '.find' - it's faster and 'more pythonic': http://stackoverflow.com/questions/18437798/find-vs-in-operation-in-string-python – Ben Sep 14 '14 at 20:06
1

You get the error

TypeError: Can't convert 'list' object to str implicitly

because with line.find(keywords) you're passing a list (keywords) to find() which expects a string.

You need to search for each keyword individually instead using a loop:

def index(filepath, keywords):
    with open(filepath) as f:
        for lineno, line in enumerate(f, start=1):
            matches = [k for k in keywords if k in line]
            if matches:
                result = "{:<15} {}".format(','.join(matches), lineno)
                print(result)


index('file.txt', ['network', 'device', 'local'])

Here I also used enumerate() to simplify line counting and string formatting to make the output aligned like in your example. The expression matches = [k for k in keywords if k in line] is a list comprehension that builds a list of all the keywords that are a substring of line.

Example output:

network,device  1
network         2
device          3
local           4
device,local    5
Community
  • 1
  • 1
Lukas Graf
  • 30,317
  • 8
  • 77
  • 92
0

If you are getting the error cannot convert list to str implicity it means that you have written an argument which will work for a string, but not for a list.

One way to fix this error:

variable = [1, 2, 3, 4, 5]

variable = str(variable)
# NOW ARGUMENT
variable = list(variable) # change it back

I'm not sure if this helps you, but others have answered your question and mine was only input for extra knowledge's sake, if you didn't already know this know you do!

W1ll1amvl
  • 1,219
  • 2
  • 16
  • 30