【问题标题】:Question on using string.replace and regex to clean data关于使用 string.replace 和 regex 清理数据的问题
【发布时间】:2020-09-25 02:36:54
【问题描述】:

我曾经问过这个问题,但由于评论者将我引导到其他一些帖子,所以它被关闭了。但是那些帖子并没有专门使用 str.replace ,这就是我应该使用的。也许那些有效,但我仍然不明白该怎么做。

这是一个问题:

这是王牌['source']:

trump['source'] = array(['<a href="http://twitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>',
       '<a href="http://twitter.com/download/android" rel="nofollow">Twitter for Android</a>',
       '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>',
       '<a href="https://studio.twitter.com" rel="nofollow">Media Studio</a>',
       '<a href="http://twitter.com/#!/download/ipad" rel="nofollow">Twitter for iPad</a>',
       '<a href="http://instagram.com" rel="nofollow">Instagram</a>',
       '<a href="https://mobile.twitter.com" rel="nofollow">Mobile Web (M5)</a>',
       '<a href="https://ads.twitter.com" rel="nofollow">Twitter Ads</a>',
       '<a href="https://periscope.tv" rel="nofollow">Periscope</a>',
       '<a href="https://studio.twitter.com" rel="nofollow">Twitter Media Studio</a>'],
      dtype=object)

我对正则表达式还很陌生,所以我真的不知道该怎么做,但是,这就是我现在所拥有的:

r = r'>(.*)<'

因为这捕获了我想要的内容并将其分组。

有谁知道如何使用 str.replace 和正则表达式来摆脱标签并将其替换为“Twitter for Iphone”等?

谢谢

【问题讨论】:

    标签: python regex replace


    【解决方案1】:

    你可以使用:

    trump['source'].str.replace(r'^<a.*nofollow">(.*)<\/a>$', r'\1')
    

    输出:

    0      Twitter for iPhone
    1     Twitter for Android
    2      Twitter Web Client
    3            Media Studio
    4        Twitter for iPad
    5               Instagram
    6         Mobile Web (M5)
    7             Twitter Ads
    8               Periscope
    9    Twitter Media Studio
    Name: source, dtype: object
    

    注意事项:

    现在,这是一个相当“懒惰”(非稳健)的正则表达式模式,但它适合手头任务的目的。以下是该模式的具体细节:

    • ^从字符串的开头开始
    • &lt;a匹配开头的锚标签
    • .* 匹配 0+ 个 any 字符
    • nofollow"&gt; 搜索“nofollow”元素以了解从哪里开始捕获
    • (.*) 捕获 0+ 次出现的任何字符(例如我们的主题文本)
    • &lt;\/a&gt;在结束锚标记处停止捕获
    • $匹配模式直到字符串结束

    replace() 函数的第二个参数是用作替换的文本。在这种情况下,请替换为第一个捕获组,标识为 r'\1'。或者你可以使用\\1

    这是我喜欢用来测试正则表达式模式的link to a site

    进一步阅读可能会对您有所帮助:

    【讨论】:

    • 别担心,伙计。万事如意!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-19
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2019-12-05
    相关资源
    最近更新 更多