float“对象没有属性”lower”

2024-04-19 06:32:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正面临着这个错误,我真的找不到它的原因。
有人能指出原因吗?

for i in tweet_raw.comments:
    mns_proc.append(processComUni(i))

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-416-439073b420d1> in <module>()
      1 for i in tweet_raw.comments:
----> 2     tweet_processed.append(processtwt(i))
      3 

<ipython-input-414-4e1b8a8fb285> in processtwt(tweet)
      4     #Convert to lower case
      5     #tweet = re.sub('RT[\s]+','',tweet)
----> 6     tweet = tweet.lower()
      7     #Convert www.* or https?://* to URL
      8     #tweet = re.sub('((www\.[\s]+)|(https?://[^\s]+))','',tweet)

AttributeError: 'float' object has no attribute 'lower'

第二个类似的错误是:

for i in tweet_raw.comments:
    tweet_proc.append(processtwt(i))

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-423-439073b420d1> in <module>()
      1 for i in tweet_raw.comments:
----> 2     tweet_proc.append(processtwt(i))
      3 

<ipython-input-421-38fab2ef704e> in processComUni(tweet)
     11         tweet=re.sub(('[http]+s?://[^\s<>"]+|www\.[^\s<>"]+'),'', tweet)
     12     #Convert @username to AT_USER
---> 13     tweet = re.sub('@[^\s]+',' ',tweet)
     14     #Remove additional white spaces
     15     tweet = re.sub('[\s]+', ' ', tweet)

C:\Users\m1027201\AppData\Local\Continuum\Anaconda\lib\re.pyc in sub(pattern, repl, string, count, flags)
    149     a callable, it's passed the match object and must return
    150     a replacement string to be used."""
--> 151     return _compile(pattern, flags).sub(repl, string, count)
    152 
    153 def subn(pattern, repl, string, count=0, flags=0):

TypeError: expected string or buffer

在将particluar tweet传递给processtwt()函数之前,是否要检查它是否为tring?对于这个错误,我甚至不知道它的失败在哪一行。


Tags: toinreconvertforinputstringraw
2条回答

试着用这个: tweet=str(tweet).lower()

最近,我遇到了许多这样的错误,在应用lower()之前将它们转换成字符串对我总是有效的。谢谢!

我的答案将比沙里尼的答案更广泛。如果要检查对象是否为str类型,我建议您使用isinstance()检查对象的type,如下所示。这是一种更像Python的方式。

tweet = "stackoverflow"

## best way of doing it
if isinstance(tweet,(str,)):
    print tweet

## other way of doing it
if type(tweet) is str:
    print tweet

## This is one more way to do it
if type(tweet) == str:
    print tweet

上面的所有操作都可以检查对象的类型是否为string。

相关问题 更多 >