python:TypeError:无法将“list”对象隐式转换为str

2024-09-28 14:53:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python 3.1.4中得到了以下错误,python3.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

更新1:

我试图从文件中的关键字创建一个列表。每行有一个关键字。我读文件是否正确?

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']的列表


Tags: 文件thetoinmap列表if关键字
2条回答

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

# 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是可能的,但不太可能。

尽管这些行已经被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):

这里使用的是一个生成器表达式。你应该了解这些,它们非常方便,也可以用来代替mapfilterlist comprehensions

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

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"

相关问题 更多 >