python - 匹配文本
问题描述
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
您的回复将不胜感激。谢谢。
解决方案
试试这个:
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
包。
推荐阅读
- c - C 是否可以将值用作枚举名称?
- html - Qt QML WebEngineView 默认工具提示在html内容中显示不正确
- kubernetes - 为什么通过 kubernetes 部署创建的 pod 名称会在其名称后附加 5 个随机字母数字字符?
- android - 找不到参数的方法 kotlin() [gradle-plugin, 1.3.20]
- swift4 - 有没有一种简单的方法可以将故事板中已经定义的约束转换为 Swift 代码?
- python - 在 Ubuntu 中为 weasyprint 安装最新的 cairo lib
- python - 如何在具有多个条件的python中快速对数字进行分类
- c# - System.OperationCanceledException 偶尔发生在带有 try catch 的异步函数中
- angular - 如何修复来自 Heroku MEAN stack CRUD App 教程的 put 请求
- python - 从熊猫数据框中删除所有数字