首页 > 解决方案 > 匹配文本

问题描述

 import re
with open("anti-adblock-killer-filters.txt")as f:
contents=f.read()
pattern=re.compile(r"[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+##")

 matches=pattern.finditer(contents)

 count=sum(1 for match in matches)

print'There are total HTML Rule With Doamin =',count

pattern=re.compile(r'##')

matches=pattern.finditer(contents)

count3=sum(1 for match in matches)

result=count3-count

print'There are total HTML hiding rule without domain is  =',result

print'There are total HTML hiding rule with and without domain is  
=',result+count

pattern=re.compile(r'\W[||]')

matches=pattern.finditer(contents)

count2=sum(1 for match in matches)

print'There are total HTTP rule with Domain Anchor  =',count2

在此代码中,符号“||” 显示域 achor 域标记表示为“域 =”我必须匹配在文件“域 =”中表示的域标记所以我的第一个问题是我应该使用哪个模式来匹配 http 规则与域锚和域标签 ?第二个问题是哪个模式将用于匹配没有域锚和域标记的 Http 规则与第三个问题相同,如果我想匹配只有域标记的 http 规则,那么模式是什么?

我正在使用 anconda python 3

您的回复将不胜感激。谢谢。

标签: pythonregex

解决方案


试试这个:

CSS="CSS"
COMMENT="COMMENT"
EXCEPTION="EXCEPTION"
FILTER="FILTER"

def is_comment(line):
    return line[0]=="!"

def is_css_rule(line):
    return '##' in line

def is_exception_rule(line):
    return '@' in line

def is_filter_rule(line):
    return not is_comment(line) and not is_css_rule(line)

def get_rule_type(line):
    if is_comment(line):
        return COMMENT
    elif is_css_rule(line):
        return CSS
    elif is_exception_rule(line):
        return EXCEPTION
    else:
        return FILTER

with open("abc.txt") as f:
    for line in f:
        print('{:12s} {!r}'.format(get_rule_type(line), line))

注意:这是使用 Python 3。此外,我们没有使用正则表达式,因此不需要包含该re包。


推荐阅读