python:TypeError:无法隐式地将'list'对象转换为str

时间:2012-02-06 18:43:47

标签: python search typeerror

我在Python 3.1.4中遇到以下错误,它曾经在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!

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

UPDATE1:

我正在尝试根据文件中的关键字创建列表。每行有一个关键字。我正确地阅读了文件吗?

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

关键字文件包含:

Keyword1
Keyword2
.
.
.
Keywordn

我想要一个名为keywords = ['Keyword1','Keyword2',...,'Keywordn']

的列表

2 个答案:

答案 0 :(得分:3)

虽然它们已被readlines()拆分,但您已拆分这些行。这应该有效:

# 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):

这里使用的是生成器表达式。您应该了解这些内容,它们非常方便,以及list comprehensions通常可用于替换mapfilter

请注意,在循环之前创建正则表达式可能更高效,如下所示:

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"

答案 1 :(得分:1)

这意味着您的关键字对象包含列表。

# this is valid:
import re
keywords=["a","b","c"]

for word in keywords: # Iterate through keywords
    if re.search(r"\b"+word+r"\b",line1):
        print "ok"

# this is not valid. This is the kind of error you get:    
keywords=[["a","b"],"c"]

for word in keywords: # Iterate through keywords
    if re.search(r"\b"+word+r"\b",line1):
        print "ok"

您应该打印word以确保您了解它是什么。您可能但不太可能希望在正则表达式中使用"".join(word)而不是word