Reputation: 21
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.
Upvotes: 1
Views: 4458
Reputation: 19766
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
Upvotes: 2
Reputation: 32580
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
Upvotes: 1
Reputation: 1269
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!
Upvotes: 0