Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否删除列表中项目的部分?_Python_Python 2.7_For Loop_Web Scraping_Trim - Fatal编程技术网

Python 是否删除列表中项目的部分?

Python 是否删除列表中项目的部分?,python,python-2.7,for-loop,web-scraping,trim,Python,Python 2.7,For Loop,Web Scraping,Trim,我将数据存储在列表中,基本上采用以下格式: ['http://www.website.com/category/apples', 'http://www.website.com/category/oranges', 'http://www.website.com/category/bananas', 'http://www.website.com/category/pears'] 此列表中包含大约900个独特的链接。我想返回类别后的文本(例如苹果,橙子等) 这可能是通过如下所示的for循环来完

我将数据存储在列表中,基本上采用以下格式:

['http://www.website.com/category/apples',
'http://www.website.com/category/oranges',
'http://www.website.com/category/bananas',
'http://www.website.com/category/pears']
此列表中包含大约900个独特的链接。我想返回
类别
后的文本(例如
苹果
橙子
等)

这可能是通过如下所示的
for
循环来完成的,但是我一直在使用正确的函数。基本上,这就是我目前所拥有的。该列表保存在
链接中

for l in links:
    new_list = l.search('category')
    return l
如何优化本质上是“修剪”列表中的每个元素

l = ['http://www.website.com/category/apples',
'http://www.website.com/category/oranges',
'http://www.website.com/category/bananas',
'http://www.website.com/category/pears']

li =  [ x[x.rindex('/')+1:] for x in l ]

print(li)
输出


['apples','oranges','panana','pears']

这是使用正则表达式的地方。将字符串与匹配“category/”的正则表达式匹配,然后使用括号运算符返回其后的字符

import re
for l in links:
    m = re.match('.+/category/(.+)', l)
    new_list.append(m.group(1))
return new_list
要进行优化,可以预编译表达式,这对于900多个字符串可能是值得的:

import re
cat = re.compile('.+/category/(.+)')
for l in links:
    new_list.append(cat.match(l).group(1))
return new_list
这可以通过列表理解而不是for循环完成:

import re
cat = re.compile('.+/category/(.+)')
return [cat.match(l).group(1) for l in links]

正则表达式,老兄。我不明白这怎么适用于这个问题,或者如果你的链接都有相同的开头,就简单地用l[31:]吧。这与
/apples
b软件相匹配,你确定吗?当我运行测试时,它按预期返回。它对那些没有“category/”的行来说并不健壮,我会在实际使用之前修复这些行,但它对测试数据很有效。根据,我本来想发布一个答案,但在这里看到两个,我没有。可能想搜索术语
category
,而不仅仅是斜杠。作品为基本范例,但要求原问题中提到的东西分类后具体说明。