pandas/python:拆分url并向数据库添加列

2024-06-26 02:53:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个单列数据库,其中有几个表单的url

'w.lejournal.fr/actualite/politique/sarkozy-terminator_1557749.html',

'w.lejournal.fr/palmares/palmares-immobilier/',

'w.lejournal.fr/actualite/societe/adeline-hazan-devient-la-nouvelle-controleuse-des-lieux-de-privation-de-liberte_1558176.html'

我想创建一个3列的数据库,第一列包含这些确切的url,第二列是页面的主要类别(Utique,或palmares),第三列包含页面的第二类(politique,或palmares immobilier,或societe)。在

我不能给我的代码,因为我不能发布网址。在

我想用Python熊猫。 第一:这是个好办法吗? 第二:如何完成连接?在

非常感谢。在


Tags: 数据库url表单htmlde页面frterminator
2条回答

使用纯Python:

data= [
    'w.lejournal.fr/actualite/politique/sarkozy-terminator_1557749.html',
    'w.lejournal.fr/palmares/palmares-immobilier/',
    'w.lejournal.fr/actualite/societe/adeline-hazan-devient-la-nouvelle-controleuse-des-lieux-de-privation-de-liberte_1558176.html'
]

result = []

for x in data:
    cols = x.split('/')
    result.append( [x, cols[1], cols[2]] )

print result

一。在

^{pr2}$

你只需要读写数据库。在


如果所有URL都以http://开头,那么您将需要获得cols[3]cols[4]

data= [
    'http://w.lejournal.fr/actualite/politique/sarkozy-terminator_1557749.html',
    'http://w.lejournal.fr/palmares/palmares-immobilier/',
    'http://w.lejournal.fr/actualite/societe/adeline-hazan-devient-la-nouvelle-controleuse-des-lieux-de-privation-de-liberte_1558176.html'
]

result = []

for x in data:
    cols = x.split('/')
    result.append( [x, cols[3], cols[4]] )

print result

不需要熊猫,regex可以非常有效地做到这一点:

import re

ts = ['w.lejournal.fr/actualite/politique/sarkozy-terminator_1557749.html',
    'w.lejournal.fr/palmares/palmares-immobilier/',
    'w.lejournal.fr/actualite/societe/adeline-hazan-devient-la-nouvelle-controleuse-des-lieux-de-privation-de-liberte_1558176.html']

rgx = r'(?<=w.lejournal.fr/)([aA-zZ]*)/([aA-zZ_-]*)(?=/)'

for url_address in ts:
    found_group = re.findall(rgx, url_address)
    for item in found_group:
        print item

这是它返回的结果:

^{pr2}$

当然,您不需要在URL列表上执行此操作

相关问题 更多 >