Python正则表达式和encod

2024-04-25 20:20:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试图找到并打印此文件中的所有电话号码。但是文件里有很多不可读的文字。 文件看起来像这样,但实际上很大: 电子

我怎样才能解码并找到所有的数字?我现在有以下代码:

import glob
import re

path = "C:\\Users\\Joey\\Downloads\\db_sdcard\\mysql\\ibdata1"
files= glob.glob(path)
for name in files:
        with open(name, 'r') as f:
            for line in f:
                print line
                match = re.search(r'(/b/d{2}-/d{8}/b)', line)
                if match:
                    found = match.group()
                    print found

当我运行脚本时,我得到以下输出:

ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ

我必须把.decode('utf8')放在哪里,剩下的代码好吗


Tags: 文件path代码nameinimportrefor
1条回答
网友
1楼 · 发布于 2024-04-25 20:20:45

尝试使用以下方法查找您的号码:

re.findall("\d{2}-\d{8}", line)

它创建符合xx-xxxxxxxx格式的所有匹配子字符串的列表,其中x是一个数字


以问题的最后一行为例:

>>> line = '   P t\xe2\x82\xac         \xc5\x92  \xc3\x98p\xe2\x82\xac Q~\xc3\x80t\xc3\xb406-23423230xx06-34893646xx secure_encryptedsecure_encrypted\xe2\x82\xac  -\xe2\x82\xac  -\xe2\x82\xac  \n'
>>> re.findall("\d{2}-\d{8}", line)
['06-23423230', '06-34893646']

全文如下:

for name in files:
    with open(name, 'r') as f:
        for line in f:
            matches = re.findall("\d{2}-\d{8}", line)
            for mt in matches:
                print mt

这将print每个匹配在单独的行上


您甚至可以同时findall整个文件中的匹配项:

for name in files:
    with open(name, 'r') as f:
        matches = re.findall("\d{2}-\d{8}", f.read())
        for mt in matches:
            print mt

相关问题 更多 >

    热门问题