首页 > 编程语言 >A Completed Python Scripter and File Handle with Matplotlib

A Completed Python Scripter and File Handle with Matplotlib

时间:2024-06-23 23:31:21浏览次数:3  
标签:__ Handle name Python Completed list item file import

import os
import requests
import requests
from bs4 import BeautifulSoup
from typing import Dict

total_div: Dict[str, BeautifulSoup] = dict()

def the_big_div(text: str):
    soup = BeautifulSoup(text, 'lxml')
    count = soup.find_all('div', class_='code-content content')
    for item in count:
            aa_ = item.find('a',class_='sortid')
            if aa_:
                total_div[aa_.text] = item
    

def download_file(url, local_file_path):
    # Ensure the directory exists
    with open(local_file_path, 'wb') as f:
        f.write(requests.get(url).content)

# Example usage:
# download_file('https://example.com/file.torrent', '/torrent/file.torrent')

def parser_the_sub_html(url: str) -> str:
    soup = BeautifulSoup(requests.get(url).text, 'lxml')
    return soup.find('a',class_='xfcomment').get('href')
    
def clean_the_file_name(name: str) -> str:
    name = name.replace(' ', '_').replace(':', '').replace('?', '').replace('*', '').replace('\n','').replace('/','_')
    if len(name) > 100:
        return name[:100]
    else:
        return name


if __name__ == '__main__':
    url = 'https://share.xfsub.org'
    for i in range(101, 202):
        sub_urls = f'https://share.xfsub.org/sort-1-{i}.html'
        the_big_div(requests.get(sub_urls).text)
        print(total_div.keys())
        
        # the address of the subitem page
        all_subitem = total_div['动画'].find_all('a', class_='name-text')
        # iterate over the subitems
        for sub_item in all_subitem:
                download_file(
                    parser_the_sub_html(
                        url + sub_item.get('href')
                    ),
                    'torrent/'+ clean_the_file_name(f'{sub_item.text}.torrent')
                )
                print(sub_item.text.strip(),'\t'*5,'________________ -> done')
import os
import re
from collections import Counter
import matplotlib.pyplot as plt
import pandas as pd

# read the list of the file name in the directory
def get_file_list(path: str) -> list:
    file_list = os.listdir(path)
    return file_list

if __name__ == '__main__':
    total_list = []
    
    plt.rcParams['font.sans-serif'] = ['SimHei']
    for item in get_file_list(r'C:\Users\123\Desktop\Project_Try\demo\src\test\java\scripts\torrent'):
        group_ = re.match(r'[\[\【](.*?)[\]\】]', item)
        if group_:
            total_list.append(group_.group(1))

    
    count = Counter(total_list)
    pd1 = pd.DataFrame(count.most_common(), columns=['资源', '数量'])
    
    plt.bar(pd1['资源'].to_list(), pd1['数量'].to_list())
    plt.title('资源统计')
    
    plt.show()

标签:__,Handle,name,Python,Completed,list,item,file,import
From: https://www.cnblogs.com/qiantaosama/p/18264146

相关文章

  • python学习笔记-09
    面向对象编程-中面向对象三大特征:封装、继承、多态。封装:把内容封装起来便于后面的使用。对于封装来讲,就是使用__init__方法将内容封装道对象中,然后通过对象直接或者self获取被封装的内容。继承:子继承父的属性和方法。多态:所谓多态就是定义时的类型和运行时的类型不一样......
  • python基础 - 数据可视化
    数据分析与可视化headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/81.0.4044.138Safari/537.36'}1、csv库Python天生支持读取CSV格式数据并且是可配置的(这个我们看到是必不可少的)。在Python里边有个......
  • python基础 - 数据实战
    """数据挖掘的流程:1-获取数据1-从固有的本地获取2-互联网动态获取2-存储数据1-大量数据数据库2-部署太大数据--使用文件存储:1-txt2-excel3-csv3-清洗数据4-算法的介入5-结果展示6-分析汇总"""importrequests,timeimportpprint,csvimportthrea......
  • python基础 - Qt5设计界面
    1、QtDesigner环境搭建1、安装PySide2库cmd里运行pipinstallPySide2-ihttps://pypi.douban.com/simple--trustedhostpypi.douban.com2、Pycharm关联DesignerFile->Settings->Tools->ExternalTools,打开页面。目的:用于快速设计、修改ui并生成.ui文件。Program......
  • python json反序列化为对象
    在Python中,将JSON数据反序列化为对象通常意味着将JSON格式的字符串转换为一个Python的数据结构(如列表、字典)或者一个自定义的类实例。虽然Python的标准库json模块不提供直接将JSON数据映射到类的实例的功能,但我们可以通过一些技巧来实现这个需求。以下是一个详细的示例,展示了如何......
  • Python实现语音转文字功能
    importosimportrequestsimporturllibimportcalendarimporttimeimportdatetimefrommoviepy.editorimportAudioFileClipfrompydubimportAudioSegmentfromaipimportAipSpeechclassDouYin:def__init__(self):self._headers={......
  • python基础 - 利用耗时计算回顾基础
    """json格式:1-自动化测试:做接口自动化测试响应数据里resp.json()接收数据2-测试开发:做后端服务--接口返回数据类型json转化方法:1-json--转--字典importjsonjson.loads()2-字典--转--jsonimportjsonjson.dumps()常见报错JSONDecodeError在j......
  • python基础 - 多线程技术
    基础概念importtimedeftest(something):print(f"我开始>>>{something}")time.sleep(2)print(f"我结束>>>{something}")"""场景:1-io密集型--阻塞sleeprequestssocket"""importthreading"&quo......
  • python基础 - socket编程基础
    一对一---服务端importsocketip_port=('127.0.0.1',9999)1-创建socket对象---socket也叫套接字sk=socket.socket()2-绑定ip端口sk.bind(ip_port)3-开启监听sk.listen()print('---socket服务器已经启动完成---')4-阻塞等待客户端来链接可以返回连接对象......
  • SQL-Python
    师从黑马程序员数据库介绍数据库就是存储数据的库数据组织:库->表->数据数据库和SQL的关系MySQL的基础命令 SQL基础SQL语言的分类SQL的语法特征DDL-库管理showDATABASES;usesys;SELECTdatabase();CREATEDATABASEtestCHARSETutf-8;SHOWDATAB......