爬虫实战——麻省理工学院新闻

news2024/9/22 7:25:24

文章目录

  • 发现宝藏
  • 一、 目标
  • 二、 浅析
  • 三、获取所有模块
  • 四、请求处理模块、版面、文章
    • 1. 分析切换页面的参数传递
    • 2. 获取共有多少页标签并遍历版面
    • 3.解析版面并保存版面信息
    • 4. 解析文章列表和文章
    • 5. 清洗文章
    • 6. 保存文章图片
  • 五、完整代码
  • 六、效果展示

发现宝藏

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。【宝藏入口】。

一、 目标

爬取news.mit.edu的字段,包含标题、内容,作者,发布时间,链接地址,文章快照 (可能需要翻墙才能访问)

二、 浅析

1.全部新闻大致分为4个模块
在这里插入图片描述

2.每个模块的标签列表大致如下

在这里插入图片描述
3.每个标签对应的文章列表大致如下

在这里插入图片描述

4.具体每篇文章对应的结构如下

在这里插入图片描述

三、获取所有模块

其实就四个模块,列举出来就好,然后对每个分别解析爬取每个模块

class MitnewsScraper:
    def __init__(self, root_url, model_url, img_output_dir):
        self.root_url = root_url
        self.model_url = model_url
        self.img_output_dir = img_output_dir
        self.headers = {
            'Referer': 'https://news.mit.edu/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/122.0.0.0 Safari/537.36',
            'Cookie': '替换成你自己的',
        }

        ...

def run():
    root_url = 'https://news.mit.edu/'
    model_urls = ['https://news.mit.edu/topic', 'https://news.mit.edu/clp',
                  'https://news.mit.edu/department', 'https://news.mit.edu/']
    output_dir = 'D:\imgs\mit-news'

    for model_url in model_urls:
        scraper = MitnewsScraper(root_url, model_url, output_dir)
        scraper.catalogue_all_pages()

四、请求处理模块、版面、文章

先处理一个模块(TOPICS)

1. 分析切换页面的参数传递

如图可知是get请求,需要传一个参数page

在这里插入图片描述

2. 获取共有多少页标签并遍历版面

实际上是获取所有的page参数,然后进行遍历获取所有的标签

在这里插入图片描述

 # 获取一个模块有多少版面
    def catalogue_all_pages(self):
        response = requests.get(self.model_url, headers=self.headers)
        soup = BeautifulSoup(response.text, 'html.parser')
        try:
            match = re.search(r'of (\d+) topics', soup.text)
            total_catalogues = int(match.group(1))
            total_pages = math.ceil(total_catalogues / 20)
            print('topics模块一共有' + match.group(1) + '个版面,' + str(total_pages) + '页数据')
            for page in range(0, total_pages):
                self.parse_catalogues(page)
                print(f"========Finished catalogues page {page + 1}========")
        except:
            self.parse_catalogues(0)

3.解析版面并保存版面信息

前三个模块的版面列表

在这里插入图片描述

第四个模块的版面列表

在这里插入图片描述

 # 解析版面列表里的版面
    def parse_catalogues(self, page):
        params = {'page': page}
        response = requests.get(self.model_url, params=params, headers=self.headers)
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            if self.root_url == self.model_url:
                catalogue_list = soup.find('div',
                                           'site-browse--recommended-section site-browse--recommended-section--schools')
                catalogues_list = catalogue_list.find_all('li')
            else:
                catalogue_list = soup.find('ul', 'page-vocabulary--views--list')
                catalogues_list = catalogue_list.find_all('li')

            for index, catalogue in enumerate(catalogues_list):
                # 操作时间
                date = datetime.now()
                # 版面标题
                catalogue_title = catalogue.find('a').get_text(strip=True)
                print('第' + str(index + 1) + '个版面标题为:' + catalogue_title)

                catalogue_href = catalogue.find('a').get('href')
                # 版面id
                catalogue_id = catalogue_href[1:]
                catalogue_url = self.root_url + catalogue_href
                print('第' + str(index + 1) + '个版面地址为:' + catalogue_url)

                # 根据版面url解析文章列表
                response = requests.get(catalogue_url, headers=self.headers)
                soup = BeautifulSoup(response.text, 'html.parser')
                match = re.search(r'of (\d+)', soup.text)
                # 查找一个版面有多少篇文章
                total_cards = int(match.group(1))
                total_pages = math.ceil(total_cards / 15)
                print(f'{catalogue_title}版面一共有{total_cards}篇文章,' + f'{total_pages}页数据')
                for page in range(0, total_pages):
                    self.parse_cards_list(page, catalogue_url, catalogue_id)
                    print(f"========Finished {catalogue_title} 版面 page {page + 1}========")

                # 连接 MongoDB 数据库服务器
                client = MongoClient('mongodb://localhost:27017/')
                # 创建或选择数据库
                db = client['mit-news']
                # 创建或选择集合
                catalogues_collection = db['catalogues']
                # 插入示例数据到 catalogues 集合
                catalogue_data = {
                    'id': catalogue_id,
                    'date': date,
                    'title': catalogue_title,
                    'url': catalogue_url,
                    'cardSize': total_cards
                }
                catalogues_collection.insert_one(catalogue_data)
            return True
        else:
            raise Exception(f"Failed to fetch page {page}. Status code: {response.status_code}")

4. 解析文章列表和文章

在这里插入图片描述
在这里插入图片描述
寻找冗余部分并删除,例如

在这里插入图片描述

 # 解析文章列表里的文章
    def parse_cards_list(self, page, url, catalogue_id):
        params = {'page': page}
        response = requests.get(url, params=params, headers=self.headers)
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            card_list = soup.find('div', 'page-term--views--list')
            cards_list = card_list.find_all('div', 'page-term--views--list-item')
            for index, card in enumerate(cards_list):
                # 对应的版面id
                catalogue_id = catalogue_id
                # 操作时间
                date = datetime.now()
                # 文章标题
                card_title = card.find('a', 'term-page--news-article--item--title--link').find('span').get_text(
                    strip=True)

                # 文章简介
                card_introduction = card.find('p', 'term-page--news-article--item--dek').find('span').get_text(
                    strip=True)
                # 文章更新时间
                publish_time = card.find('p', 'term-page--news-article--item--publication-date').find('time').get(
                    'datetime')
                updateTime = datetime.strptime(publish_time, '%Y-%m-%dT%H:%M:%SZ')
                # 文章地址
                temp_url = card.find('div', 'term-page--news-article--item--cover-image').find('a').get('href')
                url = 'https://news.mit.edu' + temp_url
                # 文章id
                pattern = r'(\w+(-\w+)*)-(\d+)'
                match = re.search(pattern, temp_url)
                card_id = str(match.group(0))
                card_response = requests.get(url, headers=self.headers)
                soup = BeautifulSoup(card_response.text, 'html.parser')
                # 原始htmldom结构
                html_title = soup.find('div', id='block-mit-page-title')
                html_content = soup.find('div', id='block-mit-content')

                # 合并标题和内容
                html_title.append(html_content)
                html_cut1 = soup.find('div', 'news-article--topics')
                html_cut2 = soup.find('div', 'news-article--archives')
                html_cut3 = soup.find('div', 'news-article--content--side-column')
                html_cut4 = soup.find('div', 'news-article--press-inquiries')
                html_cut5 = soup.find_all('div', 'visually-hidden')
                html_cut6 = soup.find('p', 'news-article--images-gallery--nav--inner')

                # 移除元素
                if html_cut1:
                    html_cut1.extract()
                if html_cut2:
                    html_cut2.extract()
                if html_cut3:
                    html_cut3.extract()
                if html_cut4:
                    html_cut4.extract()
                if html_cut5:
                    for item in html_cut5:
                        item.extract()
                if html_cut6:
                    html_cut6.extract()
                # 获取合并后的内容文本
                html_content = html_title
                # 文章作者
                author_list = html_content.find('div', 'news-article--authored-by').find_all('span')
                author = ''
                for item in author_list:
                    author = author + item.get_text()
                # 增加保留html样式的源文本
                origin_html = html_content.prettify()  # String
                # 转义网页中的图片标签
                str_html = self.transcoding_tags(origin_html)
                # 再包装成
                temp_soup = BeautifulSoup(str_html, 'html.parser')
                # 反转译文件中的插图
                str_html = self.translate_tags(temp_soup.text)
                # 绑定更新内容
                content = self.clean_content(str_html)
                # 下载图片
                imgs = []
                img_array = soup.find_all('div', 'news-article--image-item')
                for item in img_array:
                    img_url = self.root_url + item.find('img').get('data-src')
                    imgs.append(img_url)
                if len(imgs) != 0:
                    # 下载图片
                    illustrations = self.download_images(imgs, card_id)
                # 连接 MongoDB 数据库服务器
                client = MongoClient('mongodb://localhost:27017/')
                # 创建或选择数据库
                db = client['mit-news']
                # 创建或选择集合
                cards_collection = db['cards']
                # 插入示例数据到 catalogues 集合
                card_data = {
                    'id': card_id,
                    'catalogueId': catalogue_id,
                    'type': 'mit-news',
                    'date': date,
                    'title': card_title,
                    'author': author,
                    'card_introduction': card_introduction,
                    'updatetime': updateTime,
                    'url': url,
                    'html_content': str(html_content),
                    'content': content,
                    'illustrations': illustrations,
                }
                cards_collection.insert_one(card_data)

            return True
        else:
            raise Exception(f"Failed to fetch page {page}. Status code: {response.status_code}")

5. 清洗文章

 # 工具 转义标签
    def transcoding_tags(self, htmlstr):
        re_img = re.compile(r'\s*<(img.*?)>\s*', re.M)
        s = re_img.sub(r'\n @@##\1##@@ \n', htmlstr)  # IMG 转义
        return s

    # 工具 转义标签
    def translate_tags(self, htmlstr):
        re_img = re.compile(r'@@##(img.*?)##@@', re.M)
        s = re_img.sub(r'<\1>', htmlstr)  # IMG 转义
        return s

    # 清洗文章
    def clean_content(self, content):
        if content is not None:
            content = re.sub(r'\r', r'\n', content)
            content = re.sub(r'\n{2,}', '', content)
            content = re.sub(r' {6,}', '', content)
            content = re.sub(r' {3,}\n', '', content)
            content = re.sub(r'<img src="../../../image/zxbl.gif"/>', '', content)
            content = content.replace(
                '<img border="0" src="****处理标记:[Article]时, 字段 [SnapUrl] 在数据源中没有找到! ****"/> ', '')
            content = content.replace(
                ''' <!--/enpcontent<INPUT type=checkbox value=0 name=titlecheckbox sourceid="<Source>SourcePh " style="display:none">''',
                '') \
                .replace(' <!--enpcontent', '').replace('<TABLE>', '')
            content = content.replace('<P>', '').replace('<\P>', '').replace('&nbsp;', ' ')
        return content

6. 保存文章图片

# 下载图片
    def download_images(self, img_urls, card_id):
        # 根据card_id创建一个新的子目录
        images_dir = os.path.join(self.img_output_dir, card_id)
        if not os.path.exists(images_dir):
            os.makedirs(images_dir)
            downloaded_images = []
            for index, img_url in enumerate(img_urls):
                try:
                    response = requests.get(img_url, stream=True, headers=self.headers)
                    if response.status_code == 200:
                        # 从URL中提取图片文件名
                        img_name_with_extension = img_url.split('/')[-1]
                        pattern = r'^[^?]*'
                        match = re.search(pattern, img_name_with_extension)
                        img_name = match.group(0)

                        # 保存图片
                        with open(os.path.join(images_dir, img_name), 'wb') as f:
                            f.write(response.content)
                        downloaded_images.append([img_url, os.path.join(images_dir, img_name)])
                except requests.exceptions.RequestException as e:
                    print(f'请求图片时发生错误:{e}')
                except Exception as e:
                    print(f'保存图片时发生错误:{e}')
            return downloaded_images
        # 如果文件夹存在则跳过
        else:
            print(f'文章id为{card_id}的图片文件夹已经存在')
            return []

五、完整代码

import os
from datetime import datetime
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient
import re
import math

class MitnewsScraper:
    def __init__(self, root_url, model_url, img_output_dir):
        self.root_url = root_url
        self.model_url = model_url
        self.img_output_dir = img_output_dir
        self.headers = {
            'Referer': 'https://news.mit.edu/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/122.0.0.0 Safari/537.36',
            'Cookie': '_fbp=fb.1.1708485200443.423329752; _ga_HWFLFTST95=GS1.2.1708485227.1.0.1708485227.0.0.0; '
                      '_hp2_id.2065608176=%7B%22userId%22%3A%228766180140632296%22%2C%22pageviewId%22%3A'
                      '%223284419326231258%22%2C%22sessionId%22%3A%228340313071591018%22%2C%22identity%22%3Anull%2C'
                      '%22trackerVersion%22%3A%224.0%22%7D; _ga_RP0185XJY9=GS1.1.1708485227.1.0.1708485301.0.0.0; '
                      '_ga_PW4Z02MCFS=GS1.1.1709002375.3.0.1709002380.0.0.0; '
                      '_ga_03E2REYYWV=GS1.1.1709002375.3.0.1709002380.0.0.0; _gid=GA1.2.2012514268.1709124148; '
                      '_gat_UA-1592615-17=1; _gat_UA-1592615-30=1; '
                      '_ga_342NG5FVLH=GS1.1.1709256315.12.1.1709259230.0.0.0; _ga=GA1.1.1063081174.1708479841; '
                      '_ga_R8TSBG6RMB=GS1.2.1709256316.12.1.1709259230.0.0.0; '
                      '_ga_5BGKP7GP4G=GS1.2.1709256316.12.1.1709259230.0.0.0',
        }

    # 获取一个模块有多少版面
    def catalogue_all_pages(self):
        response = requests.get(self.model_url, headers=self.headers)
        soup = BeautifulSoup(response.text, 'html.parser')
        try:
            match = re.search(r'of (\d+) topics', soup.text)
            total_catalogues = int(match.group(1))
            total_pages = math.ceil(total_catalogues / 20)
            print('topics模块一共有' + match.group(1) + '个版面,' + str(total_pages) + '页数据')
            for page in range(0, total_pages):
                self.parse_catalogues(page)
                print(f"========Finished catalogues page {page + 1}========")
        except:
            self.parse_catalogues(0)

    # 解析版面列表里的版面
    def parse_catalogues(self, page):
        params = {'page': page}
        response = requests.get(self.model_url, params=params, headers=self.headers)
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            if self.root_url == self.model_url:
                catalogue_list = soup.find('div',
                                           'site-browse--recommended-section site-browse--recommended-section--schools')
                catalogues_list = catalogue_list.find_all('li')
            else:
                catalogue_list = soup.find('ul', 'page-vocabulary--views--list')
                catalogues_list = catalogue_list.find_all('li')

            for index, catalogue in enumerate(catalogues_list):
                # 操作时间
                date = datetime.now()
                # 版面标题
                catalogue_title = catalogue.find('a').get_text(strip=True)
                print('第' + str(index + 1) + '个版面标题为:' + catalogue_title)

                catalogue_href = catalogue.find('a').get('href')
                # 版面id
                catalogue_id = catalogue_href[1:]
                catalogue_url = self.root_url + catalogue_href
                print('第' + str(index + 1) + '个版面地址为:' + catalogue_url)

                # 根据版面url解析文章列表
                response = requests.get(catalogue_url, headers=self.headers)
                soup = BeautifulSoup(response.text, 'html.parser')
                match = re.search(r'of (\d+)', soup.text)
                # 查找一个版面有多少篇文章
                total_cards = int(match.group(1))
                total_pages = math.ceil(total_cards / 15)
                print(f'{catalogue_title}版面一共有{total_cards}篇文章,' + f'{total_pages}页数据')
                for page in range(0, total_pages):
                    self.parse_cards_list(page, catalogue_url, catalogue_id)
                    print(f"========Finished {catalogue_title} 版面 page {page + 1}========")

                # 连接 MongoDB 数据库服务器
                client = MongoClient('mongodb://localhost:27017/')
                # 创建或选择数据库
                db = client['mit-news']
                # 创建或选择集合
                catalogues_collection = db['catalogues']
                # 插入示例数据到 catalogues 集合
                catalogue_data = {
                    'id': catalogue_id,
                    'date': date,
                    'title': catalogue_title,
                    'url': catalogue_url,
                    'cardSize': total_cards
                }
                catalogues_collection.insert_one(catalogue_data)
            return True
        else:
            raise Exception(f"Failed to fetch page {page}. Status code: {response.status_code}")

    # 解析文章列表里的文章
    def parse_cards_list(self, page, url, catalogue_id):
        params = {'page': page}
        response = requests.get(url, params=params, headers=self.headers)
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            card_list = soup.find('div', 'page-term--views--list')
            cards_list = card_list.find_all('div', 'page-term--views--list-item')
            for index, card in enumerate(cards_list):
                # 对应的版面id
                catalogue_id = catalogue_id
                # 操作时间
                date = datetime.now()
                # 文章标题
                card_title = card.find('a', 'term-page--news-article--item--title--link').find('span').get_text(
                    strip=True)

                # 文章简介
                card_introduction = card.find('p', 'term-page--news-article--item--dek').find('span').get_text(
                    strip=True)
                # 文章更新时间
                publish_time = card.find('p', 'term-page--news-article--item--publication-date').find('time').get(
                    'datetime')
                updateTime = datetime.strptime(publish_time, '%Y-%m-%dT%H:%M:%SZ')
                # 文章地址
                temp_url = card.find('div', 'term-page--news-article--item--cover-image').find('a').get('href')
                url = 'https://news.mit.edu' + temp_url
                # 文章id
                pattern = r'(\w+(-\w+)*)-(\d+)'
                match = re.search(pattern, temp_url)
                card_id = str(match.group(0))
                card_response = requests.get(url, headers=self.headers)
                soup = BeautifulSoup(card_response.text, 'html.parser')
                # 原始htmldom结构
                html_title = soup.find('div', id='block-mit-page-title')
                html_content = soup.find('div', id='block-mit-content')

                # 合并标题和内容
                html_title.append(html_content)
                html_cut1 = soup.find('div', 'news-article--topics')
                html_cut2 = soup.find('div', 'news-article--archives')
                html_cut3 = soup.find('div', 'news-article--content--side-column')
                html_cut4 = soup.find('div', 'news-article--press-inquiries')
                html_cut5 = soup.find_all('div', 'visually-hidden')
                html_cut6 = soup.find('p', 'news-article--images-gallery--nav--inner')

                # 移除元素
                if html_cut1:
                    html_cut1.extract()
                if html_cut2:
                    html_cut2.extract()
                if html_cut3:
                    html_cut3.extract()
                if html_cut4:
                    html_cut4.extract()
                if html_cut5:
                    for item in html_cut5:
                        item.extract()
                if html_cut6:
                    html_cut6.extract()
                # 获取合并后的内容文本
                html_content = html_title
                # 文章作者
                author_list = html_content.find('div', 'news-article--authored-by').find_all('span')
                author = ''
                for item in author_list:
                    author = author + item.get_text()
                # 增加保留html样式的源文本
                origin_html = html_content.prettify()  # String
                # 转义网页中的图片标签
                str_html = self.transcoding_tags(origin_html)
                # 再包装成
                temp_soup = BeautifulSoup(str_html, 'html.parser')
                # 反转译文件中的插图
                str_html = self.translate_tags(temp_soup.text)
                # 绑定更新内容
                content = self.clean_content(str_html)
                # 下载图片
                imgs = []
                img_array = soup.find_all('div', 'news-article--image-item')
                for item in img_array:
                    img_url = self.root_url + item.find('img').get('data-src')
                    imgs.append(img_url)
                if len(imgs) != 0:
                    # 下载图片
                    illustrations = self.download_images(imgs, card_id)
                # 连接 MongoDB 数据库服务器
                client = MongoClient('mongodb://localhost:27017/')
                # 创建或选择数据库
                db = client['mit-news']
                # 创建或选择集合
                cards_collection = db['cards']
                # 插入示例数据到 catalogues 集合
                card_data = {
                    'id': card_id,
                    'catalogueId': catalogue_id,
                    'type': 'mit-news',
                    'date': date,
                    'title': card_title,
                    'author': author,
                    'card_introduction': card_introduction,
                    'updatetime': updateTime,
                    'url': url,
                    'html_content': str(html_content),
                    'content': content,
                    'illustrations': illustrations,
                }
                cards_collection.insert_one(card_data)

            return True
        else:
            raise Exception(f"Failed to fetch page {page}. Status code: {response.status_code}")

    # 下载图片
    def download_images(self, img_urls, card_id):
        # 根据card_id创建一个新的子目录
        images_dir = os.path.join(self.img_output_dir, card_id)
        if not os.path.exists(images_dir):
            os.makedirs(images_dir)
            downloaded_images = []
            for index, img_url in enumerate(img_urls):
                try:
                    response = requests.get(img_url, stream=True, headers=self.headers)
                    if response.status_code == 200:
                        # 从URL中提取图片文件名
                        img_name_with_extension = img_url.split('/')[-1]
                        pattern = r'^[^?]*'
                        match = re.search(pattern, img_name_with_extension)
                        img_name = match.group(0)

                        # 保存图片
                        with open(os.path.join(images_dir, img_name), 'wb') as f:
                            f.write(response.content)
                        downloaded_images.append([img_url, os.path.join(images_dir, img_name)])
                except requests.exceptions.RequestException as e:
                    print(f'请求图片时发生错误:{e}')
                except Exception as e:
                    print(f'保存图片时发生错误:{e}')
            return downloaded_images
        # 如果文件夹存在则跳过
        else:
            print(f'文章id为{card_id}的图片文件夹已经存在')
            return []

    # 工具 转义标签
    def transcoding_tags(self, htmlstr):
        re_img = re.compile(r'\s*<(img.*?)>\s*', re.M)
        s = re_img.sub(r'\n @@##\1##@@ \n', htmlstr)  # IMG 转义
        return s

    # 工具 转义标签
    def translate_tags(self, htmlstr):
        re_img = re.compile(r'@@##(img.*?)##@@', re.M)
        s = re_img.sub(r'<\1>', htmlstr)  # IMG 转义
        return s

    # 清洗文章
    def clean_content(self, content):
        if content is not None:
            content = re.sub(r'\r', r'\n', content)
            content = re.sub(r'\n{2,}', '', content)
            content = re.sub(r' {6,}', '', content)
            content = re.sub(r' {3,}\n', '', content)
            content = re.sub(r'<img src="../../../image/zxbl.gif"/>', '', content)
            content = content.replace(
                '<img border="0" src="****处理标记:[Article]时, 字段 [SnapUrl] 在数据源中没有找到! ****"/> ', '')
            content = content.replace(
                ''' <!--/enpcontent<INPUT type=checkbox value=0 name=titlecheckbox sourceid="<Source>SourcePh " style="display:none">''',
                '') \
                .replace(' <!--enpcontent', '').replace('<TABLE>', '')
            content = content.replace('<P>', '').replace('<\P>', '').replace('&nbsp;', ' ')
        return content

def run():
    root_url = 'https://news.mit.edu/'
    model_urls = ['https://news.mit.edu/topic', 'https://news.mit.edu/clp',
                  'https://news.mit.edu/department', 'https://news.mit.edu/']
    output_dir = 'D:\imgs\mit-news'

    for model_url in model_urls:
        scraper = MitnewsScraper(root_url, model_url, output_dir)
        scraper.catalogue_all_pages()

if __name__ == "__main__":
    run()

六、效果展示

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1487873.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

力扣周赛387

第一题 代码 package Competition.The387Competitioin;public class Demo1 {public static void main(String[] args) {}public int[] resultArray(int[] nums) {int ans[]new int[nums.length];int arr1[]new int[nums.length];int arr2[]new int[nums.length];if(nums.leng…

玩转地下管网三维建模:MagicPipe3D系统

地下管网是保障城市运行的基础设施和“生命线”。随着实景三维中国建设的推进&#xff0c;构建地下管网三维模型与地上融合的数字孪生场景&#xff0c;对于提升智慧城市管理至关重要&#xff01;针对现有三维管线建模数据差异大、建模交互弱、模型效果差、缺乏语义信息等缺陷&a…

Lua 篇(一)— 安装运行Hello World

目录 前言一、Lua 是什么&#xff1f;二、Lua和C#的区别三、安装 LuaLinux 系统上安装Mac OS X 系统上安装Window 系统上安装emmyluaRider 安装(推荐) 四、Lua学习资料 前言 Lua 是一种轻量级的嵌入式脚本语言&#xff0c;它可以与 C 语言无缝集成&#xff0c;提供了强大的编程…

开发一套小程序所需的费用取决于多个因素

随着移动互联网的发展&#xff0c;小程序已经成为许多企业和个人推广业务和服务的重要工具。 不过&#xff0c;对于很多想要开发小程序的人来说&#xff0c;最大的疑问就是开发一套小程序要花多少钱。 这个问题的答案并不是固定的&#xff0c;因为开发一个小程序的成本取决于几…

java 实现文字转语音

1. 内网环境 windows系统 选择jacob技术实现 免费的 从官网下载最新1.20jar包和dll文件 将jar包放到maven仓库中 dll文件放到jdk的bin目录下 项目代码&#xff1a; package com.example.ybxm.controller;import com.jacob.activeX.ActiveXComponent; import com.jacob.com…

代码随想录算法训练营第三十天| 回溯篇总结

文章目录 前言一、组合问题二、切割问题三、子集问题四、排列问题五、性能分析 前言 回溯法就是暴力搜索&#xff0c;并不是什么高效的算法&#xff0c;最多再剪枝一下。 组合问题&#xff1a;N个数里面按一定规则找出k个数的集合 排列问题&#xff1a;N个数按一定规则全排列…

【QT】C/C++ 文件属性设置(隐藏、只读、加密等)方法和程序示例

目录 1文件属性设置 1.1 GetFileAttributes 获取文件属性函数的返回值 1.2 SetFileAttributes 设置文件属性函数 2 文件属性设置示例 1文件属性设置 在MSDN中&#xff0c;文件总共有15种属性&#xff0c;根据磁盘的分区格式不同&#xff0c;文件的属性也会不同。 需要包含头…

Docker镜像导出/导入

Docker镜像导出/导入 一、前言 在实际操作中&#xff0c;为了便于docker镜像环境和服务配置的迁移&#xff0c;我们有时需要将已在测试环境主机上完成一系列配置的docker镜像或运行中的容器镜像导出&#xff0c;并传输到生产或其他目标环境主机上运行。为此&#xff0c;本文主…

python+Django+Neo4j中医药知识图谱与智能问答平台

文章目录 项目地址基础准备正式运行 项目地址 https://github.com/ZhChessOvO/ZeLanChao_KGQA 基础准备 请确保您的电脑有以下环境&#xff1a;python3&#xff0c;neo4j 在安装目录下进入cmd&#xff0c;输入指令“pip install -r requirement.txt”,安装需要的python库 打…

【C++精简版回顾】18.文件操作

1.文件操作头文件 2.操作文件所用到的函数 1.文件io 1.头文件 #include<fstream> 2.打开文件 &#xff08;1&#xff09;函数名 文件对象.open &#xff08;2&#xff09;函数参数 /* ios::out 可读 ios::in 可…

大模型之SORA技术学习

文章目录 sora的技术原理文字生成视频过程sora的技术优势量大质优的视频预训练库算力多&#xff0c;采样步骤多&#xff0c;更精细。GPT解释力更强&#xff0c;提示词(Prompt&#xff09;表现更好 使用场景参考 Sora改变AI认知方式&#xff0c;开启走向【世界模拟器】的史诗级的…

拉线位移编码器出现问题从哪里下手找原因

拉线位移编码器出现问题从哪里下手找原因 1、如果因接线错误导致位移编码器无信号或输出信号波动较大时&#xff0c;应按照说明书检查信号线是否连接正确。 2、拉线位移编码器的供电电压为5V&#xff0c;如果供电电压过低或过高也会引起信号线的传输&#xff0c;应检查输入电…

leetcode - 2095. Delete the Middle Node of a Linked List

Description You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list. The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes th…

【小白友好】LeetCode 打家劫舍 III

https://leetcode.cn/problems/house-robber-iii/description/ 前言 建议还是先看看动态规划的基础题再看这个。动态规划是不刷题&#xff0c;自己100%想不出来的。 基础题&#xff1a; 最大子数组和乘积最大子数组最长递增子序列 最大升序子数组和 小白想法 现在我们想遍…

使用query请求数据出现500的报错

我在写项目的时候遇到了一个问题&#xff0c;就是在存商品id的时候我将它使用了JSON.stringify的格式转换了&#xff01;&#xff01;&#xff01;于是便爆出了500这个错误&#xff01;&#xff01;&#xff01; 我将JSON.stringify的格式去除之后&#xff0c;它就正常显示了&…

Linux - 进程控制

1、进程创建 1.1、fork函数初识 在linux中fork函数时非常重要的函数&#xff0c;它从已存在进程中创建一个新进程。新进程为子进程&#xff0c;而原进程为父进程&#xff1b; #include <unistd.h> pid_t fork(void); 返回值&#xff1a;自进程中返回0&#xff0c;父进…

java常见的8种数据结构

一、线性结构&#xff1a;数组、链表、哈希表&#xff1b;队列、栈 1.数组&#xff1a; 数组是有序元素的序列&#xff0c;在内存中的分配是连续的&#xff0c;数组会为存储的元素都分配一个下标&#xff08;索引&#xff09;&#xff0c;此下标是一个自增连续的&#xff0c;访…

万村乐数字乡村系统开源代码:革命性引领,助推乡村振兴新篇章

如今&#xff0c;国际社会普遍认为信息化、数字化已是重大且不可逆转的发展趋势&#xff0c;如何让广大农村地区充分分享到这个发展带来的红利&#xff0c;从而提升农村的经济活力&#xff0c;确保村民生活质量不断优化&#xff0c;已然成为我们需要认真研究并积极解决的重大议…

美国法院命令NSO集团将其间谍软件代码交给WhatsApp

Techreport网站消息&#xff0c;近日&#xff0c;美国法院下令要求以色列间谍软件开发商NSO集团将其Pegasus间谍软件的代码交给WhatsApp。 2019年&#xff0c;NSO集团利用WhatsApp的安全漏洞对1400名用户进行了为期两周的监视。同年&#xff0c;WhatsApp向该公司提起了法律诉讼…

k8s初始化错误

报错详情&#xff1a; you can check the kubelet logs for further clues by running: ‘journalctl -u kubelet’ Alternatively, there might be issues with your Kubernetes configuration files or maybe the necessary ports are not opened. Check the status of …