简体   繁体   English

提取符号后的单词 python

[英]Extract words after a symbol in python

I have the following data where i would like to extract out source= from the values.我有以下数据,我想从这些数据中提取 source= 。 Is there a way to create a general regex function so that i can apply on other columns as well to extract words after equal sign?有没有办法创建一个通用的正则表达式 function 以便我可以应用于其他列以及提取等号后的单词?

Data                      Data2
source=book               social-media=facebook
source=book               social-media=instagram 
source=journal            social-media=facebook

Im using python and i have tried the following:我正在使用 python 并且我尝试了以下操作:

df['Data'].astype(str).str.replace(r'[a-zA-Z]\=', '', regex=True)

but it didnt work但它没有用

you can try this:你可以试试这个:

df.replace(r'[a-zA-Z]+-?[a-zA-Z]+=', '', regex=True)

It gives you the following result:它给你以下结果:

      Data      Data2
0     book   facebook
1     book  instagram
2  journal   facebook

Regex is not required in this situation:在这种情况下不需要正则表达式:

print(df['Data'].apply(lambda x : x.split('=')[-1]))
print(df['Data2'].apply(lambda x : x.split('=')[-1]))

You have to repeat the character class 1 or more times and you don't have to escape the equals sign.您必须重复字符 class 1 次或多次,并且不必转义等号。

What you can do is make the match a bit broader matching all characters except a whitespace char or an equals sign.您可以做的是使匹配更广泛一些,以匹配除空白字符或等号之外的所有字符。

Then set the result to the new value.然后将结果设置为新值。

import pandas as pd

data = [
    "source=book",
    "source=journal",
    "social-media=facebook",
    "social-media=instagram"
]

df = pd.DataFrame(data, columns=["Data"])
df['Data'] = df['Data'].astype(str).str.replace(r'[^\s=]+=', '', regex=True)
print(df)

Output Output

        Data
0       book
1    journal
2   facebook
3  instagram

If there has to be a value after the equals sign, you can also use str.extract如果等号后面必须有一个值,你也可以使用 str.extract

df['Data'] = df['Data'].astype(str).str.extract(r'[^\s=]+=([^\s=]+)')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM