首页 > 解决方案 > 从 Adblock 规则中提取域名的 RegEx

问题描述

我正在尝试从文本文件中提取所有域并将其保存到另一个文本文件中,但它显示所有域名和其他内容,并且它还返回:

ads.css 

abc.js 

Kashi.png 

我的输入字符串是:

token$script,domain=liveresult.ru

euroiphone.eu##.div-download-h

||ausujet.com/skins/common/ads.js

@@||cyberdean.fr/js/advertisement.js

biggestplayer.me##.adblock + *

 hearthhead.com,wowhead.com##.block-bg

 wowhead.com##.block-bgimg

  euroiphone.eu##.div-download-h

  euroiphone.eu##.div-download-v

 findretros.com##.fuck-adblock

 @@||ausujet.com/skins/common/ads.js

 @@||cyberdean.fr/js/advertisement.js

 @@||dbz-fantasy.com/ads.css

 @@||dev-dyod.fr/styles/ads.css

  forums.ru###mdl_adb

  ostroh.info###modal.modal-bg

  7days2die.info###nafikblock

 all-episodes.net###odin

有很多规则我必须从中提取域

我的结果应该是:

liveresult.ru

cyberdean.fr

euroiphone.eu

ausujet.com

biggestplayer.me

hearthhead.com

 wowhead.com

 euroiphone.eu

  ausujet.com

  cyberdean.fr

 dbz-fantasy.com

 dev-dyod.frforums.ru

 7days2die.infoy 

我努力了:

import re

   Domains = ['ru', 'fr' ,'eu', 'com']

 with open('easylist.txt', 'r') as f:

       a=f.read()

  result=re.findall(r'[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+',a)

  unique_result = list(set(result))

  for r in result:

     domain_name = r.split('.')[1]

     If  domain_name in domains:

      file_out.write(r+/n)

但为此我必须列出一个域列表,这是一个劳动过程,我想制作一些自动提取域的模式,忽略 ads.js、ads.css、advertising.js 等内容,所以请告诉我我在哪里做错了。

标签: regexpython-3.x

解决方案


如果要在新行中打印所有内容,则应该file_out.write(r+'\n')将每个字符串写入新行,并且可以使用删除重复项set

import re

domains = ['ru', 'fr' ,'eu', 'com']
with open('easylist.txt', 'r') as f:
    a=f.read()
    result=re.findall(r'[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+',a)
    unique_result = list(set(result))
    for r in result:
        #Extract domain name out of url
        domain_name = r.split('.')[1]
        #Check if domain name is in list of domains, only then add it
        if domain_name in domains:
            file_out.write(r)

推荐阅读