【问题标题】:How to get get multi language Title from Youtube Data API V3 and writing it into a csv File so that it is readable如何从 Youtube Data API V3 获取多语言标题并将其写入 csv 文件以便可读
【发布时间】:2020-06-07 15:18:33
【问题描述】:

我想从给定的播放列表中检索标题和 URL,并将其写入本地 csv 文件,以便在 Microsoft excel 中使用。到目前为止一切顺利,没有问题,我用https://developers.google.com/youtube/v3/code_samples/dotnet 的代码制作了一个.Net 控制台项目。 我的播放列表中的标题有多种语言,如德语、希伯来语、西班牙语和俄语。要编写 csv 文件,我在 c# 中使用 CsvHelper。问题是特殊的非英语字符在 csv 文件中显示为不可读的字符。这是我的德语播放列表代码,但它不能正确显示德语特殊字符。

using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using CsvHelper;
using CsvHelper.Configuration;
using System.Globalization;

namespace Youtube
{
internal class MyUploads
{
    [STAThread]
    static void Main(string[] args)
    {
        // Displays several properties of the neutral cultures.

        Console.WriteLine("YouTube Data API: My Uploads");
        Console.WriteLine("============================");

        try
        {
            new MyUploads().Run().Wait();
        }
        catch (AggregateException ex)
        {
            foreach (var e in ex.InnerExceptions)
            {
                Console.WriteLine("Error: " + e.Message);
            }
        }

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }

    private async Task Run()
    {
        UserCredential credential;
        using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
        {
            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                // This OAuth 2.0 access scope allows for read-only access to the authenticated 
                // user's account, but not other types of account access.
                new[] { YouTubeService.Scope.YoutubeReadonly },
                "user",
                CancellationToken.None,
                new FileDataStore(this.GetType().ToString())
            );
        }

        var youtubeService = new YouTubeService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = this.GetType().ToString()
        });

        var channelsListRequest = youtubeService.Channels.List("contentDetails");
        channelsListRequest.Mine = true;

        // Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
        var channelsListResponse = await channelsListRequest.ExecuteAsync();

        foreach (var channel in channelsListResponse.Items)
        {
            // From the API response, extract the playlist ID that identifies the list
            // of videos uploaded to the authenticated user's channel.
            var uploadsListId = "PLcHIqbEfi5uMC-GtxiSo0kFMF3bh6BQTo"; //eng "PLcHIqbEfi5uMsr-Lx0KT8mjJ-cnNYTzbW"; 
                                    //channel.ContentDetails.RelatedPlaylists.Uploads;

            Console.WriteLine("Videos in list {0}", uploadsListId);

            System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("de-DE"); //en - GB
            CsvConfiguration csvConfiguration = new CsvConfiguration(cultureInfo);
            csvConfiguration.Delimiter = ";";

            var writer = System.IO.File.CreateText("german_videos.csv");
            var csvWriter = new CsvWriter(writer,csvConfiguration);
            var nextPageToken = "";

            csvWriter.WriteField("Title");
            csvWriter.WriteField("URL");
            csvWriter.NextRecord();

            while (nextPageToken != null)
            {
                var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
                playlistItemsListRequest.PlaylistId = uploadsListId;
                playlistItemsListRequest.MaxResults = 50;
                playlistItemsListRequest.PageToken = nextPageToken;

                // Retrieve the list of videos uploaded to the authenticated user's channel.
                var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();

                foreach (var playlistItem in playlistItemsListResponse.Items)
                {
                    // Print information about each video.
                    //Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
                    csvWriter.WriteField(playlistItem.Snippet.Title);
                    csvWriter.WriteField("https://www.youtube.com/watch?v=" + playlistItem.Snippet.ResourceId.VideoId.ToString());
                    csvWriter.NextRecord();
                }

                nextPageToken = playlistItemsListResponse.NextPageToken;
            }

            csvWriter.Dispose();
            writer.Dispose();

            }
        }
    }
}

【问题讨论】:

    标签: c# csv youtube-data-api multilingual


    【解决方案1】:

    我通过写入 SQL Express 数据库、定义列 nvarchar 解决了这个问题。这解决了语言问题。

    using System;
    using System.IO;
    using System.Reflection;
    using System.Threading;
    using System.Threading.Tasks;
    
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Services;
    using Google.Apis.Upload;
    using Google.Apis.Util.Store;
    using Google.Apis.YouTube.v3;
    using Google.Apis.YouTube.v3.Data;
    using CsvHelper;
    using CsvHelper.Configuration;
    using System.Globalization;
    using System.Data.SqlClient;
    using System.Configuration;
    
    namespace Youtube
    {
    internal class MyUploads
    {
        [STAThread]
        static void Main(string[] args)
        {
            // Displays several properties of the neutral cultures.
    
            Console.WriteLine("YouTube Data API: My Uploads");
            Console.WriteLine("============================");
    
            try
            {
                //new MyUploads().Run().Wait();
                new MyUploads().Run2("PLcHIqbEfi5uMC-GtxiSo0kFMF3bh6BQTo","german").Wait();
                new MyUploads().Run2("PLcHIqbEfi5uMsr-Lx0KT8mjJ-cnNYTzbW", "english").Wait();
                new MyUploads().Run2("PLcHIqbEfi5uMQfD84IXn-k1Jxv-LN8C6U", "spanish").Wait();
                new MyUploads().Run2("PLcHIqbEfi5uMH2XkYIMeX490fAWir6S2b", "russian").Wait();
                new MyUploads().Run2("PLcHIqbEfi5uOkN9p6wj941zDG1o4maX6Z", "hebrew").Wait();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    Console.WriteLine("Error: " + e.Message);
                }
            }
    
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    
        private async Task Run2(string uploadsListId, string language)
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows for read-only access to the authenticated 
                    // user's account, but not other types of account access.
                    new[] { YouTubeService.Scope.YoutubeReadonly },
                    "user",
                    CancellationToken.None,
                    new FileDataStore(this.GetType().ToString())
                );
            }
    
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = this.GetType().ToString()
            });
            Console.WriteLine("Get Videos in list {0}", uploadsListId);
    
            string constr = ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(constr);
            con.Open();
            var nextPageToken = "";
    
            while (nextPageToken != null)
            {
                var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
                playlistItemsListRequest.PlaylistId = uploadsListId;
                playlistItemsListRequest.MaxResults = 50;
                playlistItemsListRequest.PageToken = nextPageToken;
    
                // Retrieve the list of videos uploaded to the authenticated user's channel.
                var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();
    
                foreach (var playlistItem in playlistItemsListResponse.Items)
                {
                    // Print information about each video.
                    //Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
                    SqlCommand command = new SqlCommand("INSERT INTO Videos VALUES(@playlistId,@VideoId, @Title, @Language, @position)", con);
                    command.Parameters.Add(new SqlParameter("playlistId", playlistItem.Snippet.PlaylistId));
                    command.Parameters.Add(new SqlParameter("VideoId", playlistItem.Snippet.ResourceId.VideoId));
                    command.Parameters.Add(new SqlParameter("Title", playlistItem.Snippet.Title));
                    command.Parameters.Add(new SqlParameter("Language", language));
                    command.Parameters.Add(new SqlParameter("position", playlistItem.Snippet.Position));
                    command.ExecuteNonQuery();
                    command.Dispose();
                }
    
                nextPageToken = playlistItemsListResponse.NextPageToken;
            }
            //clean up
            con.Close();
            con.Dispose();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-17
      • 1970-01-01
      • 2016-11-01
      • 2013-06-30
      • 2019-08-23
      • 1970-01-01
      • 2019-10-05
      • 2019-07-27
      • 1970-01-01
      相关资源
      最近更新 更多