【问题标题】:Pandas: create a function to delete linksPandas:创建删除链接的功能
【发布时间】:2023-01-06 23:18:03
【问题描述】:

我需要一个函数来删除 pandas DataFrame 中我的 oldText 列(超过 1000 行)中的链接。 我使用正则表达式创建了它,但它不起作用。这是我的代码:

def remove_links(text):
    text = re.sub(r'http\S+', '', text) 
    text = text.strip('[link]') 

    return text

df['newText'] = df['oldText'].apply(remove_links)

我没有错误,代码什么也没做

【问题讨论】:

  • 知道包含该列的内容会很有趣。
  • oldText 列的实际格式是什么?链接是如何表示的?您可以使用urlparse 来解析文本并提取/丢弃 URL 组件。
  • 我认为文本中无法识别正则表达式。我会检查并确保它在函数本身的级别上工作。

标签: python pandas


【解决方案1】:

你的代码对我有用: 格式文件:

oldText
https://abc.xy/oldText asd
https://abc.xy/oldTe asd
https://abc.xy/oldT
https://abc.xy/old
https://abc.xy/ol

代码:

import pandas as pd
import re


def remove_links(text):
    text = re.sub(r'httpS+', '', text) 
    text = text.strip('[link]') 

    return text


df = pd.read_csv('test2.csv')
df['newText'] = df['oldText'].apply(remove_links)
print(df)

结果:

                       oldText newText
0  https://abc.xy/oldText asd     asd
1    https://abc.xy/oldTe asd     asd
2         https://abc.xy/oldT        
3          https://abc.xy/old        
4           https://abc.xy/ol        

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2018-10-18
    • 1970-01-01
    • 2013-11-07
    • 2019-01-07
    • 2018-07-31
    相关资源
    最近更新 更多