【问题标题】:Adding exception to "AttributeError" python将异常添加到“AttributeError”python
【发布时间】: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


【解决方案1】:

search() 时可以使用re.IGNORECASE 标志。
这样您就不需要处理lower() 或异常。

def word_in_text(word, text):
    print text
    if re.search(word, text, re.IGNORECASE):
        return True
    else:
        return False

例如,如果我运行:

from __future__ import unicode_literals # see edit notes
import re

text = "??CANCION! You &amp"
word = "you"

def word_in_text(word, text):
    print(text)
    if re.search(word, text, re.IGNORECASE):
        return True
    else:
        return False

print(word_in_text(word, text))

输出是:

??CANCION! You &amp
True

编辑

对于 Python 2,您应该在脚本顶部添加 from __future__ import unicode_literals,以确保将所有内容编码为 UTF-8。
你可以阅读更多关于它的信息here

【讨论】:

  • 对我来说它说:- text = "??CANCETION!你 &amp" :对无效字符号的引用:第 1 行,第 1 列113
  • 我试过了,但它仍然给出了同样的错误。我正在使用 Eclipse for python,你认为这可能是问题吗?
  • 不太可能。您可以编辑您的问题并添加完整的错误日志吗?
  • 你有一个TypeError(日志中的最后一行)。确保 textword 的类型为 string。您可以在search() 行之前尝试print type(text)print type(text)
  • 感谢您的帮助。它将类型显示为 Unicode。我添加了 from _future_ import unicode_literals。作为一种解决方法,我试图去除 Unicode 字符的文本,但它给出了以下错误 UnicodeEncodeError: 'ascii' codec can't encode characters in position 16-19: ordinal not in range(128) .你有什么建议吗?我使用 pandas 将所有推文放在数据框中
猜你喜欢
  • 2016-03-04
  • 2016-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-19
  • 2015-11-17
  • 2014-07-17
  • 1970-01-01
相关资源
最近更新 更多