Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am getting the following error with Python 3.1.4 which used to work well in Python 2.7.2.

TypeError: Can't convert 'list' object to str implicitly. I get the error on the if statement. Please let me know how to fix this. Thanks!

In

for word in keywords: # Iterate through keywords
    if re.search(r"\b"+word+r"\b",line1):           #Search kewords in the input line

Update1:

I am trying to create a list from keywords which is in a file. Each line has one keyword. Am I reading the file properly?

keyword_file=r"KEYWORDS.txt"
f0=open(keyword_file,'r')
keywords = map(lambda a: a.split('\n'),map(str.lower, f0.readlines()))

keyword file contains:

Keyword1
Keyword2
.
.
.
Keywordn

I want a list called keywords = ['Keyword1','Keyword2',...,'Keywordn']

like image 976
Zenvega Avatar asked Sep 20 '25 03:09

Zenvega


1 Answers

You split the lines although they have already been split by readlines(). This should work:

# actually no need for readline() here, the file object can be
# directly used to iterate over the lines
keywords = (line.strip().lower() for line in f0)
# ...
for word in keywords:
  if re.search(r"\b"+word+r"\b",line1):

What's used here is a generator expression. You should learn about those, they are quite handy, as well as about list comprehensions which can often be used to replace map and filter.

Note that it might be more performant to create the regular expression before the loop, like this:

keywords = (line.strip() for line in f0)
# use re.escape here in case the keyword contains a special regex character
regex = r'\b({0})\b'.format('|'.join(map(re.escape, keywords)))
# pre-compile the regex (build up the state machine)
regex = re.compile(regex, re.IGNORECASE)

# inside the loop over the lines
if regex.search(line1)
  print "ok"
like image 131
Niklas B. Avatar answered Sep 22 '25 16:09

Niklas B.