使用 Regex 从 Twitter 数据中提取用户名

Using Regex for extracting Usernames from Twitter Data

我正在尝试借助正则表达式从 Twitter 文本中提取姓名。但是,尽管存在模式,值 returned 是 none,但事实并非如此。我的代码哪里有问题,我不知道。我正在使用 jupyter 实验室。

示例文本是 pd.Series full_text

0    RT @SeamusHughes: The Taliban Stamp of approva...
1    RT @WFaqiri: Taliban and Afghan groups find co...
2    RT @DavidCornDC: Imagine what Fox News would h...
3    RT @DavidCornDC: Imagine what Fox News would h...
4    RT @billroggio: Even if you are inclined to tr...
5    RT @billroggio: I am sure we will hear the arg...
6    RT @KFILE: This did happen and it went exactly...
Name: full_text, dtype: object

我定义的函数如下:

def extract_user(text):
        m = re.search(r"RT\s@\w+:", text)
        return m  

并且,我应用上面的函数如下:

full_text.apply(extract_user)

但是我在return中得到的值如下:

0        None
1        None
2        None
3        None
4        None
         ... 
21299    None
21300    None
21301    None
21302    None
21303    None
Name: full_text, Length: 21304, dtype: object

您可以使用下面的代码做更多的事情

df.A.str.extract(r"(@\w+)") #A is the column name

输出

    0
0   @SeamusHughes
1   @WFaqiri
2   @DavidCornDC
3   @DavidCornDC
4   @billroggio
5   @billroggio
6   @KFILE

如果您只需要名称而不需要 @ 符号,请使用 df.A.str.extract(r"@(\w+)")

输出

    0
0   SeamusHughes
1   WFaqiri
2   DavidCornDC
3   DavidCornDC
4   billroggio
5   billroggio
6   KFILE

在其中使用 lambda 函数怎么样:

>>> df[0].apply(lambda text: re.search(r'RT\s@([^:]+)',text).group(1))
0    SeamusHughes
1         WFaqiri
2     DavidCornDC
3     DavidCornDC
4      billroggio
5      billroggio
6           KFILE

为了彻底,将它们放在一起:

import pandas as pd
data = [['RT @SeamusHughes: The Taliban Stamp of approva...'],['RT @WFaqiri: Taliban and Afghan groups find co...'],['RT @DavidCornDC: Imagine what Fox News would h...'],['RT @DavidCornDC: Imagine what Fox News would h...'],['RT @billroggio: Even if you are inclined to tr...'],['RT @billroggio: I am sure we will hear the arg...'],['RT @KFILE: This did happen and it went exactly...']]
df=pd.DataFrame(data)
df[0].apply(lambda text: re.search(r'RT\s@([^:]+)',text).group(1))

# 0    SeamusHughes
# 1         WFaqiri
# 2     DavidCornDC
# 3     DavidCornDC
# 4      billroggio
# 5      billroggio
# 6           KFILE
# Name: 0, dtype: object

发生这种情况的原因是因为你的函数(extract_user) returns:

0    <re.Match object; span=(5, 22), match='RT @Sea...
1    <re.Match object; span=(5, 17), match='RT @WFa...
2    <re.Match object; span=(5, 21), match='RT @Dav...
3    ...

现在我不是专家所以对此持保留态度,但我的猜测是 pandas 没有 dtype 来处理 <re.Match> 对象你的函数 returns 所以它用 None 处理它。如果您想更深入地研究已处理的数据类型,请查看 很好的答案。

因此,假设您希望所有的方法保持不变,并进行最小的更改,这里是您的函数示例,只需返回每个 <re.Match> 的第一项 ([0])对象。

def extract_user(text):
         m = re.search(r"RT\s@\w+:", text)
         return m[0]                        # <-- here

stuff = df.iloc[:, 0].apply(extract_user)

print(stuff)

0    RT @SeamusHughes:
1         RT @WFaqiri:
2     RT @DavidCornDC:
3     RT @DavidCornDC:
4      RT @billroggio:
5      RT @billroggio:
6           RT @KFILE:

希望澄清事情。