【问题标题】:python: TypeError: Can't convert 'list' object to str implicitlypython:TypeError:无法将'list'对象隐式转换为str
【发布时间】:2014-03-04 00:40:01
【问题描述】:

我在使用 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

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

【问题讨论】:

  • wordline1 似乎是列表而不是字符串,如您所料。哪个我不知道,你必须提供更多代码。
  • 这里的列表是什么?第 1 行? re.search() 采用要搜索的模式和字符串,而不是列表。
  • @NiklasB。你是对的。 Word 是一个列表。请参阅我的编辑问题以获取更多信息。我无法以正确的格式导入列表。
  • @Pradeep:我没有看到任何更新..

标签: python search typeerror


【解决方案1】:

尽管它们已经被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"

【讨论】:

  • 谢谢尼克拉斯。关键字列表不是预期格式。我无法查看它,因为它是一个生成器对象。可以让它看起来像keywords = ['Keyword1','Keyword2',...,'Keywordn']
  • 是的,通过使用列表推导来代替:keywords = [x.strip().lower() for x in f0.readlines()]
  • 删除.readlines()。您无需在此处创建行列表。
  • 如果keywords 可能重叠,那么较长的关键字应该放在较短的关键字之前(如果您想提取匹配项)。
  • @J.F.Sebastian:你对第一个建议是对的,我编辑了这个(复制原始代码时一定错过了它)。不过,我不太明白您的第二点:为什么要首选较长的关键字?我们也使用\b 来匹配单词边界。
【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 2017-08-31
    • 2012-11-19
    • 2015-12-10
    • 2014-08-03
    • 2017-08-24
    相关资源
    最近更新 更多