如何向此标记化函数添加错误捕获

时间:2014-07-06 00:56:02

标签: python indexing tokenize

我正在尝试使用split()在推文中查找主题标签和用户。

以下是我试图从

中提取信息的推文示例

One version of a layout I never put live. This was from sometime in January. http://t.co/PppHGmRa

我正在使用此代码:

def get_tweet_meta(tweet_text, tweet_id, auth):
     api = auth
     words = tweet_text.split(" ")
     hashtags = []
     at_user = []
     meta = {}
     print tweet_text
     for word in words:
         print word
         print word[0]
         if word[0] is '#':
             hashtags.append(word)
         if word[0] is '@':
             at_user.append(word)

      print hashtags
      print at_user

我到了推文中的in,我发现错误,我认为是与额外的空格有关。

in
i

Traceback (most recent call last):
  File "twitterBot3.py", line 111, in <module>
    get_tweet_meta(value, key, auth)
  File "twitterBot3.py", line 86, in get_tweet_meta
    print word[0]
IndexError: string index out of range

代码使用规范化的文本块,但在这里抛出错误,任何想法。感谢

1 个答案:

答案 0 :(得分:2)

你在单个空间分裂;如果一行中有多个空格,这可能会导致空结果。

使用str.split() 不带参数来拆分任意空格并删除开始和结束空格:

>>> s = ' spaces  in odd    places  '
>>> s.split(' ')
['', 'spaces', '', 'in', 'odd', '', '', '', 'places', '', '']
>>> s.split()
['spaces', 'in', 'odd', 'places']

word[0]在空字符串上然后引发IndexError

你永远不应该使用is来测试相等性;使用==is测试对象标识。实际使用的任何字符串或整数都是一种特殊情况,其中解释器实现选择通过在内部重用对象来优化某些方面(内存,字典访问等)。