Python script to read all the data under the folder and extract keyword data from it

Error 1:

UnicodeDecodeError: 'mbcs' codec can't decode byte 0xfc in position 3094: No mapping for the Unicode character exists in the target code page.
# 原因:
# 编码不对

1.
There are so many files in the demand scenario \capture_info folder, and the ip field needs to be extracted from all the text
Insert picture description here
Insert picture description here

2. Code example

def test_data2():
    # 1.从文件中读取数据
    # 2.从文件中去提取ip
    path = file_path  # 文件夹目录 将路径设置为变量参数
    files = os.listdir(path)  # 得到文件夹下的所有文件名称
    txt_list = []  # 定义空列表来存储

    for file in files:  # 遍历文件夹
        position = path + '\\' + file  # 构造绝对路径,"\\",其中一个'\'为转义符
        print(position)
        with open(position, mode='r', encoding='utf-8') as f:  # 打开文件 #注意编码格式
            date = f.read()  # 读取文件
            txt_list.append(date)  # 添加到数组中
    txt_list = ','.join(txt_list)  # 转化为非数组类型
    # print(type(txt_list))
    # print(txt_list)

    # 提取ip
    ips = re.findall(r"@ijiami_ip:(.+?)@jvm_stack_start", txt_list)
    print(ips)   # 返回一个数组

    # 统计ip出现次数
    ip_num = Counter(ips)
    print(ip_num)

    # 将结果输出到一个txt中
    mylog = open('E:\\mycode\\result_num1.txt', mode='a', encoding='utf-8')
    print(ip_num, file=mylog)
    print(domain_num, file=mylog)
    print('\n')
    mylog.close()
# 运行结果:
Counter({
    
    '113.96.232.29:80': 31, '39.103.130.125:443': 2, '110.185.186.35:443': 2, '203.209.230.17:443': 1, '42.120.158.121:80': 1........

Guess you like

Origin blog.csdn.net/u014150715/article/details/109468762