根据特定字符串过滤网站

时间:2018-01-25 13:30:54

标签: python string pandas

我目前正在对网址进行分析,并希望找到与特定字词匹配的网址。这些网址位于pandas DataFrame列中,我想过滤网址标题中的特定字词。

到目前为止我做了什么:

data['new'] = data['SOURCEURL'].str.extract("(" + "|".join(filter3) +")", expand=False)

这个问题是我应用的过滤器是缩写(' ecb'),它通常也用在链接的末尾。

http://www.ntnews.com.au/news/national/senate-president-stephen-parry-believes-he-is-a-british-citizen/news-story/b2d3a3442544937f85508135401a3f84?nk=f19e52d2acd9588ecb494c03f21fed8c-1509598074

在最后的' /' -section中。我怎样才能过滤掉ecb'出现在文字周围的出现?像www.xyz.com/news/national/ecb-press-realease/b2dse332313这样的东西并没有提取散列中的ecb或类似的东西。这是否可以轻松实现?

非常感谢!

3 个答案:

答案 0 :(得分:2)

也许您可以将URL拆分为单词并过滤掉所有不在英语词典中的单词?例如,使用PyEnchant

import enchant
d = enchant.Dict("en_US")
filtered_words = [x for x in words if d.check(x)]

答案 1 :(得分:1)

一个简单的解决方案是在最后/之前检查字符串:

df = pd.DataFrame({'SOURCEURL':['http://au/news/nat/cit/news-story/b2ecb',
                                'http://au/news/nat/cit/news-story/b2d88ecb494']})

print (df)
                                       SOURCEURL
0        http://au/news/nat/cit/news-story/b2ecb
1  http://au/news/nat/cit/news-story/b2d88ecb494

filter3 = ['ecb']
df['new'] = (df['SOURCEURL'].str.rsplit('/', 1).str[0]
                            .str.extract("(" + "|".join(filter3) +")", expand=False))

另一个类似的解决方案:

filter3 = ['ecb']
df['new'] = (df['SOURCEURL'].str.extract('(.*)/', expand=False)
                            .str.extract("(" + "|".join(filter3) +")", expand=False))
print (df)
                                       SOURCEURL  new
0        http://au/news/nat/cit/news-story/b2ecb  NaN
1  http://au/news/nat/cit/news-story/b2d88ecb494  NaN

答案 2 :(得分:1)

这里有另一种可能的方法。您可能希望排除在网址末尾传递的参数,我相信这是您唯一能看到的地方吗?或者= =

在这种情况下,您可以将每个拆分字符串部分评估为True / False,并返回总和的布尔值以获得True / False。

validation = bool(sum([True if sub in x and "?" not in x and '=' not in x else False for x in url.split('/')]))