Adding exception to "AttributeError" python
<p>So, I have some tweets with some special characters and shapes. I am trying to find a word in those tweets by converting them to lower case. The function throws an "AttributeError" when it encounters those special characters and hence, I want to change my function in a way that it skips those records and processes others.</p>

<p>Can I add exception to "AttributeError" in python. I want it to act more like an "iferror resume next"/Error handling statement.</p>

<p>I am currently using:-</p>

<pre><code>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
</code></pre>

<p>error post using @galah92 recommendations :-</p>

<pre><code>Traceback (most recent call last):
  File "&lt;input&gt;", line 1, in &lt;module&gt;
  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 "&lt;input&gt;", line 1, in &lt;lambda&gt;
  File "&lt;input&gt;", 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
</code></pre>

<p>I am new to Python and self learning it. Any help will be really appreciated.</p>

<p>You can use <code>re.IGNORECASE</code> flag when you <code>search()</code>.<br>
That way you don't need to deal with <code>lower()</code> or exceptions.</p>

<pre><code>def word_in_text(word, text):
    print text
    if re.search(word, text, re.IGNORECASE):
        return True
    else:
        return False
</code></pre>

<hr>

<p>As an example, if I run:</p>

<pre><code>from __future__ import unicode_literals # see edit notes
import re

text = "í ¼í¾µí ½í´¥CANCION! You &amp;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))
</code></pre>

<p>The output is:</p>

<pre><code>í ¼í¾µí ½í´¥CANCION! You &amp;amp
True
</code></pre>

<hr>

<p><strong>EDIT</strong></p>

<p>For Python 2, you should add <code>from __future__ import unicode_literals</code> at the top of your script to make sure you encode everything to UTF-8.<br>
You can read more about it <a href="http://stackoverflow.com/questions/23370025/what-is-unicode-literals-used-for">here</a>.</p>

python python-2.7 python-3.x