[英]Python script with AttributeError: 'tuple' object has no attribute 'lower'
I'm kind of new to python. 我是python的新手。 A python script has been running fine - it now dies with the following error: python脚本运行良好-现在死于以下错误:
File "/var/newspaper/myscript.py", line 495, in <listcomp>
return sorted(set([x.lower() for x in self.regex.findall(text)] +
self.regex_a.findall(text)))
AttributeError: 'tuple' object has no attribute 'lower'
The lines around the error are as follows: 错误周围的行如下所示:
def findall_unique(self, text):
"""
Find all unique occurrences of keywords in text.
"""
# Ordinary words are being lower(), abbreviations are returned as is
return sorted(set([x.lower() for x in self.regex.findall(text)] + self.regex_a.findall(text)))
def get_related_ids(self, words):
result = set(self.related_ids.get(x.lower()) for x in words)
result = [x for x in result if x is not None]
result.sort()
return result
I guess a check is needed to see if x has an attribute lower before attempting to do the set/sorted operations... if it does that return is ok, if not then something else has to be done... can you suggest some code that will fix the error? 我猜想在尝试执行设置/排序操作之前需要检查x是否具有较低的属性...如果返回的结果是可以的,如果没有,则必须做其他事情...您能建议一些吗?代码将解决该错误?
That should work: 那应该工作:
[x.lower() for y in self.regex.findall(text) for x in y]
y
is a tuple, and this lowers all elements of the tuple. y
是一个元组,这会降低该元组的所有元素。
The docs for re.findall
say: "If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group." re.findall
的文档说:“如果模式中存在一个或多个组,则返回一个组列表;如果模式中有多个组,则这将是一个元组列表。” This is where the list of tuples comes from. 这是元组列表的来源。 Groups here means that you have parentheses in your regexp that define matching groups. 这里的组意味着您在正则表达式中有括号来定义匹配的组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.