国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

ホームページ バックエンド開発 Python チュートリアル 【Python】Bilibiliビデオコメントとバレットチャットを処理?分析するスクリプト

【Python】Bilibiliビデオコメントとバレットチャットを処理?分析するスクリプト

Jan 05, 2025 pm 07:54 PM

[Python] A Script for Processing and Analysing Bilibili Video Comments and Bullet Chats

免責(zé)事項: 個人的な學(xué)習(xí)および研究目的のみ。それ以外の用途での使用は固く禁止されています。

導(dǎo)入

このスクリプトは人文科學(xué)の學(xué)術(shù)目的、特にネットワーク プラットフォームの談話分析の研究のために開発されました。 Bilibili の弾丸チャットとコメントを包括的に調(diào)査できます。サブカルチャーと社會問題に関連する膨大な內(nèi)容に焦點が當(dāng)てられており (レビューされた資料に基づく)、徹底的な調(diào)査、分析、補足、要約が必要です。

內(nèi)容が膨大であるため、結(jié)果はリンクに表示されます。

サブカルチャーの観點からのコメントと弾丸チャットの研究:
https://nbviewer.org/github/Excalibra/scripts/blob/main/d-ipynb/サブカルチャーの視點からのレビューとブレットスクリーンリサーチ.ipynb

計畫では、「サブカルチャー」セクションと「社會問題」セクションの調(diào)査を完了してから公開する予定でした。ただし、この分野の研究者や學(xué)生のニーズを考慮して、現(xiàn)在は共有されています。

特徴と原理

スクリプトの機能:

  1. ビデオのタイトル、著者、公開日、再生回數(shù)、お気に入り、共有、累積箇條書きチャット、コメント數(shù)、ビデオの説明、カテゴリ、ビデオのリンク、カバー畫像のリンクなどのデータを収集します。

  2. 感情スコア、品詞分析、タイムスタンプ、ユーザー ID を含む 100 件の箇條書きチャットを抽出します。

  3. 上位 20 件のコメントと、いいね!、感情スコア、トピックへの返信、メンバーシップ ID、名前、およびコメントのタイムスタンプを取得します。

強化された機能:

  1. バレットチャット: ユーザー名、誕生日、登録日、フォロワー數(shù)、フォロー數(shù) (Cookie を使用)。

  2. コメント: コメント投稿者の IP ロケーションを表示します (Web インターフェース経由)。

  3. 感情中央値、単語頻度統(tǒng)計、ワード クラウド、棒グラフを含むデータを Excel ファイルに出力します。

動作原理:

API を使用して JSON 情報を取得し、それを Excel ファイルに処理し、SnowNLP、ThuNLP、Jieba などの言語モデルを使用してテキスト セグメンテーション、ストップワード フィルタリング、品詞分析、単語頻度統(tǒng)計を行います。 Matplotlib はグラフの生成に使用されます。

すぐに始めましょう

(Windows ユーザーは pip と python を使用できます。Mac ユーザーはデフォルトで pip3 と python3 を使用する必要があります。)

スクリプト ソース コード: GitHub リポジトリ。

前提條件ライブラリ:
必要なライブラリをインストールします:

pip3 install --no-cache-dir -r https://ghproxy.com/https://github.com/Excalibra/scripts/blob/main/d-txt/requirements.txt

次に、スクリプトを?qū)g行します (オンライン):

python3 -c "$(curl -fsSL https://ghproxy.com/https://github.com/Excalibra/scripts/blob/main/d-python/get_bv_baseinfo.py)"

import json
import time
import requests
import os
from datetime import datetime
import re
from bs4 import BeautifulSoup
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font
from snownlp import SnowNLP
import statistics
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import platform
import thulac
import matplotlib.font_manager as fm
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By


'''''''''

# Reference Links

## General

Regex: https://regex101.com/
Zhihu - Two ways to obtain Bilibili video bullet comments using Python: https://zhuanlan.zhihu.com/p/609154366
Juejin - Parsing Bilibili video bullet comments: https://juejin.cn/post/7137928570080329741
CSDN - Bilibili historical bullet comment crawler: https://blog.csdn.net/sinat_18665801/article/details/104519838
CSDN - How to write a Bilibili bullet comment crawler: https://blog.csdn.net/bigbigsman/article/details/78639053?utm_source=app
Bilibili - Bilibili bullet comment notes: https://www.bilibili.com/read/cv5187469/
Bilibili third-party API: https://www.bookstack.cn/read/BilibiliAPIDocs/README.md

## Reverse Lookup by UID

https://github.com/esterTion/BiliBili_crc2mid
https://github.com/cwuom/GetDanmuSender/blob/main/main.py
https://github.com/Aruelius/crc32-crack

## User Basic Information

https://api.bilibili.com/x/space/acc/info?mid=298220126
https://github.com/ria-klee/bilibili-uid
https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/user/space.md

## Comments

https://www.bilibili.com/read/cv10120255/
https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/comment/readme.md

## JSON

https://json-schema.apifox.cn
https://bbs.huaweicloud.com/blogs/279515
https://www.cnblogs.com/mashukui/p/16972826.html

## Cookie

https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Cookies

## Unpacking

https://www.cnblogs.com/will-wu/p/13251545.html
https://www.w3schools.com/python/python_tuples.asp

'''''''''''

class BilibiliAPI:
    @staticmethod
    # Parse video link basic information JSON and return it in JSON format
    def get_bv_json(video_url):
        video_id = re.findall(r'BV\w+', video_url)[0]
        api_url = f'https://api.bilibili.com/x/web-interface/view?bvid={video_id}'
        bv_json = requests.get(api_url).json()
        return bv_json

    @staticmethod
    # Parse video link bullet comments XML using the 'cid' field in JSON
    def get_danmu_xml(bv_json):
        cid = bv_json['data']["cid"]
        api_url = f'https://comment.bilibili.com/{cid}.xml'
        danmu_xml = api_url
        return danmu_xml

    @staticmethod
    # Parse video link comments JSON using the 'aid' field in JSON
    def get_comment_json(bv_json):
        aid = bv_json['data']["aid"]
        api_url = f'https://api.bilibili.com/x/v2/reply/main?next=1&type=1&oid={aid}'
        comment_json = requests.get(api_url).json()
        return comment_json

    @staticmethod
    # Enhanced parsing of video link comments JSON using the 'aid' field in JSON
    def get_comment_json_to_webui(bv_json):
        aid = bv_json['data']["aid"]
        api_url = f'https://api.bilibili.com/x/v2/reply/main?next=1&type=1&oid={aid}'

        # Determine the current operating system type
        if platform.system() == "Windows":
            # Windows platform
            driver = webdriver.Chrome()
        else:
            # Other platforms
            driver = webdriver.Chrome(ChromeDriverManager().install())

        # Provide login time
        print("Provide 45 seconds for Bilibili login")
        time.sleep(45)

        # Open the link
        driver.get(api_url)

        # Provide view effect time
        print("Provide 15 seconds to check the effects")
        time.sleep(15)

        # Find the <pre class="brush:php;toolbar:false"> element
        pre_element = driver.find_element(By.TAG_NAME, 'pre')

        # Get the text content of the element
        text_content = pre_element.text

        # Close WebDriver
        driver.quit()

        return text_content

    @staticmethod
    # Traverse user information and return basic parameters, preparing for XLSX write-in
    def get_user_card(mid, cookies):
            api_url = f'https://account.bilibili.com/api/member/getCardByMid?mid={mid}'
            try:
                response = requests.get(api_url, cookies=cookies)
                user_card_json = response.json()
            except json.JSONDecodeError:
                return {"error": "Failed to parse JSON. Ensure a good network environment. Too many API calls might trigger restrictions; try again later."}

            if 'message' in user_card_json:
                message = user_card_json['message']
                if 'request blocked' in message or 'frequent requests' in message:
                    return {"warning": "Ensure a good network environment. Too many API calls might trigger restrictions; try again later."}

            return user_card_json

class CRC32Checker:
    ''''''''''
    # CRC32 cracking
    # Source: https://github.com/Aruelius/crc32-crack
    # Author: Aruelius
    # Note: This section has been slightly adjusted and encapsulated as a class for easier use.
    '''''''''

    CRCPOLYNOMIAL = 0xEDB88320
    crctable = [0 for x in range(256)]

    def __init__(self):
        self.create_table()

    def create_table(self):
        # Create a CRC table for quick CRC value computation
        for i in range(256):
            crcreg = i
            for _ in range(8):
                if (crcreg & 1) != 0:
                    crcreg = self.CRCPOLYNOMIAL ^ (crcreg >> 1)
                else:
                    crcreg = crcreg >> 1
            self.crctable[i] = crcreg

    def crc32(self, string):
        # Compute the CRC32 value for the given string
        crcstart = 0xFFFFFFFF
        for i in range(len(str(string))):
            index = (crcstart ^ ord(str(string)[i])) & 255
            crcstart = (crcstart >> 8) ^ self.crctable[index]
        return crcstart

    def crc32_last_index(self, string):
        # Compute the last character CRC table index for a given string
        crcstart = 0xFFFFFFFF
        for i in range(len(str(string))):
            index = (crcstart ^ ord(str(string)[i])) & 255
            crcstart = (crcstart >> 8) ^ self.crctable[index]
        return index

    def get_crc_index(self, t):
        # Find the index in the CRC table corresponding to the highest byte value
        for i in range(256):
            if self.crctable[i] >> 24 == t:
                return i
        return -1

    def deep_check(self, i, index):
        # Deep check based on index and previous CRC32 values to verify the assumption
        string = ""
        tc = 0x00
        hashcode = self.crc32(i)
        tc = hashcode & 0xff ^ index[2]
        if not (tc <= 57 and tc >= 48):
            return [0]
        string += str(tc - 48)
        hashcode = self.crctable[index[2]] ^ (hashcode >> 8)
        tc = hashcode & 0xff ^ index[1]
        if not (tc <= 57 and tc >= 48):
            return [0]
        string += str(tc - 48)
        hashcode = self.crctable[index[1]] ^ (hashcode >> 8)
        tc = hashcode & 0xff ^ index[0]
        if not (tc <= 57 and tc >= 48):
            return [0]
        string += str(tc - 48)
        hashcode = self.crctable[index[0]] ^ (hashcode >> 8)
        return [1, string]

    def main(self, string):
        # Main function to compute and validate CRC32 for the given string
        index = [0 for x in range(4)]
        i = 0
        ht = int(f"0x{string}", 16) ^ 0xffffffff
        for i in range(3, -1, -1):
            index[3-i] = self.get_crc_index(ht >> (i*8))
            snum = self.crctable[index[3-i]]
            ht ^= snum >> ((3-i)*8)
        for i in range(100000000):
            lastindex = self.crc32_last_index(i)
            if lastindex == index[3]:
                deepCheckData = self.deep_check(i, index)
                if deepCheckData[0]:
                    break
        if i == 100000000:
            return -1
        return f"{i}{deepCheckData[1]}"
class Tools:
    @staticmethod
    # Get save path and format
    def get_save():
        return os.path.join(os.path.join(os.path.expanduser("~"), "Desktop"),
                            "Bilibili_Video_Analysis_{}.xlsx".format(datetime.now().strftime('%Y-%m-%d')))

    @staticmethod
    # Format timestamp
    def format_timestamp(timestamp):
        dt_object = datetime.fromtimestamp(timestamp)
        formatted_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
        return formatted_time

    @staticmethod
    # Calculate sentiment score
    def calculate_sentiment_score(text):
        s = SnowNLP(text)
        sentiment_score = s.sentiments
        return sentiment_score

    @staticmethod
    # Generate a word cloud
    def get_word_cloud(sheet_name: str, workbook: Workbook):
        sheet = workbook[sheet_name]

        # Read frequency data
        words = []
        frequencies = []
        for row in sheet.iter_rows(min_row=2, values_only=True):
            words.append(row[0])
            frequencies.append(row[1])

        system = platform.system()

        if system == 'Darwin':  # macOS
            font_path = '/System/Library/Fonts/STHeiti Light.ttc'
        elif system == 'Windows':
            font_path = 'C:/Windows/Fonts/simhei.ttf'
        else:  # Other OS
            font_path = 'simhei.ttf'

        wordcloud = WordCloud(background_color='white', max_words=100, font_path=font_path)
        word_frequency = dict(zip(words, frequencies))
        wordcloud.generate_from_frequencies(word_frequency)

        plt.imshow(wordcloud, interpolation='bilinear')
        plt.axis('off')
        plt.show()

    @staticmethod
    # Generate horizontal statistics chart
    def get_word_chart(sheet_name: str, workbook):
        sheet = workbook[sheet_name]

        words = []
        frequencies = []
        for row in sheet.iter_rows(min_row=2, values_only=True):
            words.append(row[0])
            frequencies.append(row[1])

        system = platform.system()

        if system == 'Darwin':  
            font_path = '/System/Library/Fonts/STHeiti Light.ttc'
        elif system == 'Windows':
            font_path = 'C:/Windows/Fonts/simhei.ttf'
        else:  
            font_path = 'simhei.ttf'

        custom_font = fm.FontProperties(fname=font_path)

        fig, ax = plt.subplots()
        ax.barh(words, frequencies)
        ax.set_xlabel("Frequency", fontproperties=custom_font)
        ax.set_ylabel("Words", fontproperties=custom_font)

        plt.yticks(fontproperties=custom_font)

        plt.show()

    @staticmethod
    def get_user_info_by_card(user_card_json):
        info = {
            'name': "N/A", 'birthday': "N/A", 'regtime': "N/A",
            'fans': "N/A", 'friend': "N/A"
        }

        try:
            info['name'] = user_card_json['card']['name']
            info['birthday'] = user_card_json['card']['birthday']
            info['regtime'] = Tools.format_timestamp(int(user_card_json['card']['regtime']))
            info['fans'] = user_card_json['card']['fans']
            info['friend'] = user_card_json['card']['friend']
        except KeyError:
            pass

        return tuple(info.values())

class BilibiliExcel:
    @staticmethod
    # Write video basic information
    def write_base_info(workbook, bv_json):
        sheet = workbook.create_sheet(title="Video Info")
        headers = ["Video Title", "Author", "Publish Time", "Views", "Favorites", "Shares", "Total Bullet Comments",
                   "Comments Count", "Video Description", "Category", "Video Link", "Thumbnail Link"]
        sheet.append(headers)

        data = [bv_json["data"]["title"],
                bv_json["data"]["owner"]["name"],
                Tools.format_timestamp(bv_json["data"]["pubdate"]),
                bv_json["data"]["stat"]["view"],
                bv_json["data"]["stat"]["favorite"],
                bv_json["data"]["stat"]["share"],
                bv_json["data"]["stat"]["danmaku"],
                bv_json["data"]["stat"]["reply"],
                bv_json["data"]["desc"],
                bv_json["data"]["tname"],
                video_url,
                bv_json["data"]["pic"]]

        sheet.append(data)

    @staticmethod
    def save_workbook(workbook):
        workbook.save(Tools.get_save())

class PrintInfo:
    # Print basic information
    @staticmethod
    def base_message():
        if 'Windows' == platform.system():
            os.system('cls')
        else:
            os.system('clear')

        text = '''
        ************************************

        Bilibili Video Analysis v2023.6.26
        Author: Github.com/hoochanlon
        Project URL: https://github.com/hoochanlon/scripts

        Features:
        1. Analyze and visualize Bilibili video data.

        Disclaimer: For research and learning purposes only.

        ************************************
        '''
        print(text.center(50, ' '))

if __name__ == '__main__':
    PrintInfo.base_message()

    while True:
        video_url = input("Paste the Bilibili video link: ")
        if re.match(r'.*BV\w+', video_url):
            break
        else:
            print("Invalid link format. Please re-enter.")

    bv_json = BilibiliAPI.get_bv_json(video_url)
    workbook = Workbook()
    workbook.remove(workbook.active)
    BilibiliExcel.write_base_info(workbook, bv_json)
    BilibiliExcel.save_workbook(workbook)

使用上の注意:

  • Cookie の入力を簡素化するには、key=value; を使用できます。 「a=a;」などの形式にすると、不要な手順をスキップできます。
  • IP の場所を表示するには、Web ドライバー経由で Bilibili アカウントにログインする必要があります。

以上が【Python】Bilibiliビデオコメントとバレットチャットを処理?分析するスクリプトの詳細內(nèi)容です。詳細については、PHP 中國語 Web サイトの他の関連記事を參照してください。

このウェブサイトの聲明
この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當(dāng)する法的責(zé)任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脫衣畫像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード寫真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

寫真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中國語版

SublimeText3 中國語版

中國語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統(tǒng)合開発環(huán)境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Pythonの不適格またはPytestフレームワークは、自動テストをどのように促進しますか? Pythonの不適格またはPytestフレームワークは、自動テストをどのように促進しますか? Jun 19, 2025 am 01:10 AM

Pythonの不適格でPytestは、自動テストの書き込み、整理、および実行を簡素化する2つの広く使用されているテストフレームワークです。 1.両方とも、テストケースの自動発見をサポートし、明確なテスト構(gòu)造を提供します。 pytestはより簡潔で、テスト\ _から始まる関數(shù)が必要です。 2。それらはすべて組み込みのアサーションサポートを持っています:Unittestはアサートエクイアル、アサートトルー、およびその他の方法を提供しますが、Pytestは拡張されたアサートステートメントを使用して障害の詳細を自動的に表示します。 3.すべてがテストの準(zhǔn)備とクリーニングを処理するためのメカニズムを持っています:un

Pythonは、NumpyやPandasなどのライブラリとのデータ分析と操作にどのように使用できますか? Pythonは、NumpyやPandasなどのライブラリとのデータ分析と操作にどのように使用できますか? Jun 19, 2025 am 01:04 AM

pythonisidealfordataanalysisduetonumpyandpandas.1)numpyexcelsatnumericalcompitations withfast、多次元路面およびベクトル化された分離likenp.sqrt()

動的なプログラミング技術(shù)とは何ですか?また、Pythonでそれらを使用するにはどうすればよいですか? 動的なプログラミング技術(shù)とは何ですか?また、Pythonでそれらを使用するにはどうすればよいですか? Jun 20, 2025 am 12:57 AM

動的プログラミング(DP)は、複雑な問題をより単純なサブ問題に分解し、結(jié)果を保存して繰り返し計算を回避することにより、ソリューションプロセスを最適化します。主な方法は2つあります。1。トップダウン(暗記):問題を再帰的に分解し、キャッシュを使用して中間結(jié)果を保存します。 2。ボトムアップ(表):基本的な狀況からソリューションを繰り返し構(gòu)築します。フィボナッチシーケンス、バックパッキングの問題など、最大/最小値、最適なソリューション、または重複するサブ問題が必要なシナリオに適しています。Pythonでは、デコレータまたはアレイを通じて実裝でき、再帰的な関係を特定し、ベンチマークの狀況を定義し、空間の複雑さを最適化することに注意する必要があります。

__iter__と__next__を使用してPythonにカスタムイテレーターを?qū)g裝するにはどうすればよいですか? __iter__と__next__を使用してPythonにカスタムイテレーターを?qū)g裝するにはどうすればよいですか? Jun 19, 2025 am 01:12 AM

カスタムイテレーターを?qū)g裝するには、クラス內(nèi)の__iter__および__next__メソッドを定義する必要があります。 __iter__メソッドは、ループなどの反復(fù)環(huán)境と互換性があるように、通常は自己の反復(fù)オブジェクト自體を返します。 __next__メソッドは、各反復(fù)の値を制御し、シーケンスの次の要素を返し、アイテムがもうない場合、停止例外をスローする必要があります。 statusステータスを正しく追跡する必要があり、無限のループを避けるために終了條件を設(shè)定する必要があります。 fileファイルラインフィルタリングなどの複雑なロジック、およびリソースクリーニングとメモリ管理に注意を払ってください。 simple単純なロジックについては、代わりにジェネレーター関數(shù)の収率を使用することを検討できますが、特定のシナリオに基づいて適切な方法を選択する必要があります。

Pythonプログラミング言語とそのエコシステムの新たな傾向または將來の方向性は何ですか? Pythonプログラミング言語とそのエコシステムの新たな傾向または將來の方向性は何ですか? Jun 19, 2025 am 01:09 AM

Pythonの將來の傾向には、パフォーマンスの最適化、より強力なタイププロンプト、代替ランタイムの増加、およびAI/MLフィールドの継続的な成長が含まれます。第一に、CPYTHONは最適化を続け、スタートアップのより速い時間、機能通話の最適化、および提案された整數(shù)操作を通じてパフォーマンスを向上させ続けています。第二に、タイプのプロンプトは、コードセキュリティと開発エクスペリエンスを強化するために、言語とツールチェーンに深く統(tǒng)合されています。第三に、PyscriptやNuitkaなどの代替のランタイムは、新しい機能とパフォーマンスの利點を提供します。最後に、AIとデータサイエンスの分野は拡大し続けており、新興図書館はより効率的な開発と統(tǒng)合を促進します。これらの傾向は、Pythonが常に技術(shù)の変化に適応し、その主要な位置を維持していることを示しています。

ソケットを使用してPythonでネットワークプログラミングを?qū)g行するにはどうすればよいですか? ソケットを使用してPythonでネットワークプログラミングを?qū)g行するにはどうすればよいですか? Jun 20, 2025 am 12:56 AM

Pythonのソケットモジュールは、クライアントおよびサーバーアプリケーションの構(gòu)築に適した低レベルのネットワーク通信機能を提供するネットワークプログラミングの基礎(chǔ)です?;镜膜蔜CPサーバーを設(shè)定するには、Socket.Socket()を使用してオブジェクトを作成し、アドレスとポートをバインドし、.listen()を呼び出して接続をリッスンし、.accept()を介してクライアント接続を受け入れる必要があります。 TCPクライアントを構(gòu)築するには、ソケットオブジェクトを作成し、.connect()を呼び出してサーバーに接続する必要があります。次に、.sendall()を使用してデータと.recv()を送信して応答を受信します。複數(shù)のクライアントを処理するには、1つを使用できます。スレッド:接続するたびに新しいスレッドを起動します。 2。非同期I/O:たとえば、Asyncioライブラリは非ブロッキング通信を?qū)g現(xiàn)できます。注意すべきこと

Pythonクラスの多型 Pythonクラスの多型 Jul 05, 2025 am 02:58 AM

Pythonオブジェクト指向プログラミングのコアコンセプトであるPythonは、「1つのインターフェイス、複數(shù)の実裝」を指し、異なるタイプのオブジェクトの統(tǒng)一処理を可能にします。 1。多型は、メソッドの書き換えを通じて実裝されます。サブクラスは、親クラスの方法を再定義できます。たとえば、Animal ClassのSOCK()方法は、犬と貓のサブクラスに異なる実裝を持っています。 2.多型の実用的な用途には、グラフィカルドローイングプログラムでdraw()メソッドを均一に呼び出すなど、コード構(gòu)造を簡素化し、スケーラビリティを向上させる、ゲーム開発における異なる文字の共通の動作の処理などが含まれます。 3. Pythonの実裝多型を満たす必要があります:親クラスはメソッドを定義し、子クラスはメソッドを上書きしますが、同じ親クラスの継承は必要ありません。オブジェクトが同じ方法を?qū)g裝する限り、これは「アヒル型」と呼ばれます。 4.注意すべきことには、メンテナンスが含まれます

Pythonでリストをスライスするにはどうすればよいですか? Pythonでリストをスライスするにはどうすればよいですか? Jun 20, 2025 am 12:51 AM

Pythonリストスライスに対するコアの答えは、[start:end:step]構(gòu)文をマスターし、その動作を理解することです。 1.リストスライスの基本形式はリスト[start:end:step]です。ここで、開始は開始インデックス(含まれています)、endはend index(含まれていません)、ステップはステップサイズです。 2。デフォルトで開始を省略して、0から開始を開始し、デフォルトで終了して終了し、デフォルトでステップを1に省略します。 3。my_list[:n]を使用して最初のnアイテムを取得し、my_list [-n:]を使用して最後のnアイテムを取得します。 4.ステップを使用して、my_list [:: 2]などの要素をスキップして、均一な數(shù)字と負のステップ値を取得できます。 5.一般的な誤解には、終了インデックスが含まれません

See all articles