从数据框的列中查找所有网站链接、分组和计数 - Python

Find all website links, group and count from column of dataframe - Python

我有一个包含以下列的数据框:Date,Time,Tweet,Client,Client Simplified Tweet 列有时包含一个网站 link。 我正在尝试定义一个函数,该函数提取此 link 在推文中显示的次数以及它是哪个 link。

我不想要整个函数的答案。在我将所有这些编程到一个函数之前,我现在正在努力使用 findall 函数:

import pandas as pd
import re

csv_doc = pd.read_csv("/home/datasci/prog_datasci_2/activities/activity_2/data/TrumpTweets.csv")

URL = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', csv_doc)

我得到的错误是:

TypeError                                 Traceback (most recent call last)
<ipython-input-20-0085f7a99b7a> in <module>
      7 # csv_doc.head()
      8 tweets = csv_doc.Tweet
----> 9 URL= re.split('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',tweets)
     10 
     11 # URL = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', csv_doc[Tweets])

/usr/lib/python3.8/re.py in split(pattern, string, maxsplit, flags)
    229     and the remainder of the string is returned as the final element
    230     of the list."""
--> 231     return _compile(pattern, flags).split(string, maxsplit)
    232 
    233 def findall(pattern, string, flags=0):

TypeError: expected string or bytes-like object

你能告诉我哪里出了问题吗? 谢谢

  1. 尝试在字符串前加r。它会告诉 Python 这是一个正则表达式模式

  2. 也重新打包主要处理单个字符串,而不是列表或字符串系列。您可以尝试使用这样的简单列表理解:

[re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',x) for x in csv_doc.Tweet]