【发布时间】:2017-01-15 16:33:42
【问题描述】:
所以,我有一些带有一些特殊字符和形状的推文。我试图通过将它们转换为小写来在这些推文中找到一个单词。该函数在遇到这些特殊字符时会引发“AttributeError”,因此,我想以跳过这些记录并处理其他记录的方式更改我的函数。
我可以在 python 中为“AttributeError”添加异常吗?我希望它更像一个“iferror resume next”/错误处理语句。
我目前正在使用:-
def word_in_text(word, text):
try:
print text
word = word.lower()
text = text.lower()
match = re.search(word, text)
if match:
return True
else:
return False
except(AttributeError, Exception) as e:
continue
使用@galah92 推荐的错误帖子:-
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Python27\lib\site-packages\pandas\core\series.py", line 2220, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas\src\inference.pyx", line 1088, in pandas.lib.map_infer (pandas\lib.c:63043)
File "<input>", line 1, in <lambda>
File "<input>", line 3, in word_in_text
File "C:\Python27\lib\re.py", line 146, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
我是 Python 新手,并且是自学的。任何帮助将不胜感激。
【问题讨论】:
-
你的意思是
except? -
我试过
except,但它也确实有效。 -
导致
AttributeError的逻辑是什么?您是否考虑过使用内置函数hasattr()? -
Just strip you string 之前使用
lower()。 -
我试过剥离,看起来像列 dtype=object 而不是字符串,你能建议我怎么解决吗?推文的示例是 ????????CANCETION!你和
标签: python python-2.7 python-3.x