使用Regex从Dataframe的指定列中提取标点符号

使用Regex从Dataframe的指定列中提取标点符号

在这篇文章中,我们将看到如何使用Regex提取数据框架指定列中使用的标点符号。

首先,我们正在制作包含所有标点符号的正则表达式。[!”\$%&\'()+,\-.\/:;=#@?[\\\]^_`{|}~] 然后我们将特定列的每一行传递给re.findall()函数以提取标点符号,然后将提取的标点符号分配给数据框架的新列。

re.findall()函数用于提取****,作为一个字符串的列表,所有不重叠的模式匹配。字符串被从左到右扫描,并按照找到的顺序返回匹配的字符串。

语法: re.findall(regex, string)

返回:字符串中模式的所有非重叠匹配,作为一个字符串的列表。

现在,让我们创建一个数据框架。

# import required libraries
import pandas as pd
import re
  
# creating Dataframe with
# name and their comments
df = pd.DataFrame({
    'Name' : ['Akash', 'Ashish', 'Ayush',
              'Diksha' , 'Radhika'],
    
    'Comments': ['Hey! Akash how r u' , 
                 'Why are you asking this to me?' ,
                 'Today, what we are going to do.' ,
                 'No plans for today why?' ,
                 'Wedding plans, what are you saying?']},
    
    columns = ['Name', 'Comments']
    )
  
# show the Dataframe
df

输出:

使用Regex从Dataframe的指定列中提取标点符号

现在,从列注释中提取标点符号。

# define a function for extracting
# the punctuations
def check_find_punctuations(text):
    
    # regular expression containing
    # all punctuation
    result = re.findall(r'[!"\$%&\'()*+,\-.\/:;=#@?\[\\\]^_`{|}~]*', 
                        text)
      
    # form a string
    string = "".join(result)
      
    # list of strings return
    return list(string)
    
# creating new column name
# as a punctuation_used and 
# applying user defined function
# on each rows of Comments column
df['punctuation_used'] = df['Comments'].apply(
                         lambda x : check_find_punctuations(x)
                         )
  
# show the Dataframe
df

输出:

使用Regex从Dataframe的指定列中提取标点符号

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程