Python 3.x 获取类型错误,需要字符串或字节,如对象
我正在处理一个有tweet的数据集,我试图在tweet中找到对其他用户的提及,这些tweet可以没有提及,也可以只提及一个或多个用户 以下是数据帧的头部: 以下是我创建的用于提取推文中提及列表的函数:Python 3.x 获取类型错误,需要字符串或字节,如对象,python-3.x,pandas,Python 3.x,Pandas,我正在处理一个有tweet的数据集,我试图在tweet中找到对其他用户的提及,这些tweet可以没有提及,也可以只提及一个或多个用户 以下是数据帧的头部: 以下是我创建的用于提取推文中提及列表的函数: def getMention(text): mention = re.findall('(^|[^@\w])@(\w{1,15})', text) if len(mention) > 0: return [x[1] for x in mention]
def getMention(text):
mention = re.findall('(^|[^@\w])@(\w{1,15})', text)
if len(mention) > 0:
return [x[1] for x in mention]
else:
return None
我正在尝试在DataFrame中创建一个新列,并使用以下代码应用该函数:
df['mention'] = df['text'].apply(getMention)
运行此代码时,我遇到以下错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-43-426da09a8770> in <module>
----> 1 df['mention'] = df['text'].apply(getMention)
~/anaconda3_501/lib/python3.6/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
3192 else:
3193 values = self.astype(object).values
-> 3194 mapped = lib.map_infer(values, f, convert=convert_dtype)
3195
3196 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/src/inference.pyx in pandas._libs.lib.map_infer()
<ipython-input-42-d27373022afd> in getMention(text)
1 def getMention(text):
2
----> 3 mention = re.findall('(^|[^@\w])@(\w{1,15})', text)
4 if len(mention) > 0:
5 return [x[1] for x in mention]
~/anaconda3_501/lib/python3.6/re.py in findall(pattern, string, flags)
220
221 Empty matches are included in the result."""
--> 222 return _compile(pattern, flags).findall(string)
223
224 def finditer(pattern, string, flags=0):
TypeError: expected string or bytes-like object
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在里面
---->1 df['notify']=df['text'].应用(getnotify)
应用中的~/anaconda3_501/lib/python3.6/site-packages/pandas/core/series.py(self、func、convert\u dtype、args、**kwds)
3192其他:
3193 values=self.astype(object.values)
->3194 mapped=lib.map\u推断(值,f,convert=convert\u数据类型)
3195
3196如果len(映射)和isinstance(映射[0],系列):
pandas/_libs/src/inference.pyx在pandas中。_libs.lib.map_infere()
在GetTide中(文本)
1.提及(文本):
2.
---->3提及=re.findall(“(^ |[^@\w])@(\w{1,15})”,文本)
4如果len(提及)>0:
5返回[x[1]表示提及的x]
findall中的~/anaconda3_501/lib/python3.6/re.py(模式、字符串、标志)
220
结果中包含221个空匹配项。”“”
-->222返回编译(模式、标志).findall(字符串)
223
224 def finditer(模式、字符串、标志=0):
TypeError:应为字符串或类似字节的对象
我无法发表评论(没有足够的代表),因此我建议对错误进行故障排除。
findall似乎引发了一个异常,因为文本不是字符串,所以您可能希望使用以下方法检查文本的实际类型:
def get提纲(文本):
打印(打印(文本))
提提=re.findall(r'(^ |[^@\w])@(\w{1,15}),文本)
如果len(提及)>0:
返回[x[1]表示提及的x]
其他:
一无所获
(或调试器,如果您知道如何使用)
如果文本可以转换成字符串,可以试试这个吗
def get提纲(文本):
提提=re.findall(r'(^ |[^@\w])@(\w{1,15}),str(text))
如果len(提及)>0:
返回[x[1]表示提及的x]
其他:
一无所获
注意:不要忘记您的regexp前面的
r'…'
,以避免特殊字符被解释谢谢!其中一行被视为浮点型,我曾尝试打印列值,但我确实注意到一个空行,但我假设它仍将被视为空字符串,而不是NaN值。Just对代码做了一点小小的修改,只打印出不是str的值的类型,这样更容易找到类型错误。