読者です 読者をやめる 読者になる 読者になる

Pythonでフォルダ内のファイル一覧をパス無しで取得する

import glob
import os

files = glob.glob('D:/CEN_list/CEN_list/bin/Debug/file/*.txt')

for f in files:
    (dirname,filename)=os.path.split(f)
    print(filename)

Journalのタイトルをリストアップする

c#
using System.Text;
using System.IO;
namespace html
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamWriter writer = new StreamWriter("article.html", true, Encoding.UTF8);
            writer.WriteLine("<ol>");
            for (int volume = 1; volume < 6; volume++)
            {
                for (int issue = 1; issue < 3; issue++)
                {
                    for (int page = 1; page < 3; page++)
                    {
                        string myfile = volume.ToString() + "_" + issue.ToString() + "_" + page.ToString() + ".html";
                        StreamReader sr = new StreamReader(myfile, Encoding.UTF8);
                        string mytext = sr.ReadToEnd();
                        sr.Close();
                        System.Text.RegularExpressions.Regex x =
                            new System.Text.RegularExpressions.Regex(
                                @"(<ol>)(.*?)(</ol>)", System.Text.RegularExpressions.RegexOptions.IgnoreCase
                                | System.Text.RegularExpressions.RegexOptions.Singleline);
                        System.Text.RegularExpressions.Match mat = x.Match(mytext);
                        string newtext = System.Text.RegularExpressions.Regex.Replace(mat.Value.ToString(), "<div class=\"actions\">(.*?)</div>", "", System.Text.RegularExpressions.RegexOptions.Singleline);
                        newtext = System.Text.RegularExpressions.Regex.Replace(newtext, "<p class=\"no-access-message\">(.*?)</p>", "", System.Text.RegularExpressions.RegexOptions.Singleline);
                        newtext = System.Text.RegularExpressions.Regex.Replace(newtext, "</ol>", "", System.Text.RegularExpressions.RegexOptions.Singleline);
                        newtext = System.Text.RegularExpressions.Regex.Replace(newtext, "<ol>", "", System.Text.RegularExpressions.RegexOptions.Singleline);
                        writer.WriteLine(newtext);
                    }
                }
            }
            writer.WriteLine("</ol>");
            writer.Close();
        }
    }
}

Journalのタイトルを一括ダウンロード

c#
namespace download
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int volume = 1; volume < 6; volume++)
            {
                for (int issue = 1; issue < 3; issue++)
                {
                    for (int page = 1; page < 3; page++)
                    {
                        string url = "http://link.springer.com/journal/13730/" + volume.ToString() + "/" + issue.ToString() + "/page/" + page.ToString();
                        string output = volume.ToString() + "_" + issue.ToString() + "_" + page.ToString() + ".html";
                        System.Net.WebClient wc = new System.Net.WebClient();
                        wc.DownloadFile(url, output);
                        wc.Dispose();
                    }
                }
            }
        }
    }
}

英語学習のためのアプリを作る

c#

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="英語問題" Height="350" Width="816" Initialized="Window_Initialized">
    <Grid>
        <TextBlock x:Name="textblock1" HorizontalAlignment="Left" Margin="42,38,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="111" Height="24" Grid.ColumnSpan="2"/>
        <TextBox x:Name="textbox1" HorizontalAlignment="Left" Height="122" Margin="42,87,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="715" TextChanged="textbox1_TextChanged" FontSize="18"/>
        <Button x:Name="sound" Content="音声" Margin="40,245,0,0" VerticalAlignment="Top" Height="24" IsEnabled="False" Click="sound_Click" HorizontalAlignment="Left" Width="104"/>
        <Button x:Name="next" Content="新しい問題" HorizontalAlignment="Left" Margin="190,245,0,0" VerticalAlignment="Top" Width="104" Height="24" Click="next_Click"/>
        <Button x:Name="again" Content="やり直し" HorizontalAlignment="Left" Margin="340,245,0,0" VerticalAlignment="Top" Width="104" Height="24" Click="again_Click"/>
        <Button x:Name="answer" Content="正解をみる" HorizontalAlignment="Left" Margin="490,245,0,0" VerticalAlignment="Top" Width="104" Height="24" Click="answer_Click" IsEnabled="False"/>
    </Grid>
</Window>

Window1.xaml

<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="解答" Height="300" Width="820">
    <Grid>
        <TextBox x:Name="textbox1" HorizontalAlignment="Left" Height="122" Margin="42,87,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="715" FontSize="18">
        </TextBox>
    </Grid>
</Window>

Main.Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.Diagnostics;

namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        string[] all_data;
        string[] kugiri = { "\r\n" };
        int all_q;
        int q_num;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Initialized(object sender, EventArgs e)
        {
            string txt = File.ReadAllText("english.txt",System.Text.Encoding.GetEncoding("Shift_JIS"));
            all_data = txt.Split(kugiri, StringSplitOptions.RemoveEmptyEntries);
            all_q = all_data.Length;
            next.Focus();
        }

        private void textbox1_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (textbox1.Text == all_data[q_num])
            {
                MessageBox.Show("正解");
                next.Focus();
            }
        }

        private void next_Click(object sender, RoutedEventArgs e)
        {
            sound.IsEnabled = true;
            answer.IsEnabled = true;
            Random rand = new Random();
            q_num = rand.Next(all_q);
            textblock1.Text = (q_num + 1).ToString();
            textbox1.Text = "";
            textbox1.Focus();
        }

        private void sound_Click(object sender, RoutedEventArgs e)
        {
            string pass;
            pass = (q_num + 1).ToString() + ".mp3";
            Process.Start(pass);
        }

        private void again_Click(object sender, RoutedEventArgs e)
        {
            textbox1.Text = "";
            textbox1.Focus();
        }

        private void answer_Click(object sender, RoutedEventArgs e)
        {
            Window1 win = new Window1();
            win.textbox1.Text = all_data[q_num];
            win.ShowDialog();
        }
    }
}

Rの結果をPDFに出力する(文字化け対応)

R

Rの結果をテキストファイルとpngファイルに出力する。
それらをWordで受け取ってPDFファイルに出力する。
Rのコード

data(iris)
mydata <- iris

比較 <- c("Sepal.Length","Sepal.Width","Petal.Length","Petal.Width")

counter=1
for (hikaku in 1:length(比較)){
		
		セトサ <- subset(mydata,Species=="setosa")[[比較[hikaku]]]
		バージーカラー <- subset(mydata,Species=="versicolor")[[比較[hikaku]]]

		if (mean(セトサ)>mean(バージーカラー)) side <-"greater"
		if (mean(セトサ)<mean(バージーカラー)) side <-"less"
		if (mean(セトサ)==mean(バージーカラー)) side <-"two.sided"

		sink(paste("R結果1_",counter,".txt",sep=""))
		cat(比較[hikaku])
		cat("\n")
		cat("\n")
		cat("セトサ\n")
		print(summary(セトサ))
		cat("\n")
		cat("バージーカラー\n")
		print(summary(バージーカラー))
		sink()

		sink(paste("R結果2_",counter,".txt",sep=""))
		print(t.test(セトサ,バージーカラー,alternative=side))
		print(wilcox.test(セトサ,バージーカラー,alternative=side))
		sink()

		png(paste("R図_",counter,".png",sep=""),width = 360, height = 360)
		boxplot(セトサ,バージーカラー,names=c("セトサ","バージーカラー"))
		dev.off()
		counter <- counter+1
	}

shell.exec("PDF.docm")

Word VBAのコード

Option Explicit

Private Sub Document_Open()
        
        Dim current_path As String
        Dim picture_path As String
        Dim output_path As String
        
        current_path = ThisDocument.Path
        output_path = current_path & "/" & "検定結果.pdf"
        
        Dim counter As Integer
        Dim myFileName As String
        
        myFileName = Dir(ThisDocument.Path & "/" & "R図_" & "*.png")
        counter = 0
        Do Until myFileName = ""
            counter = counter + 1
            myFileName = Dir()
        Loop
        
        Dim i As Integer
        For i = 1 To counter
            Dim FSO As Object, TextFile As Object, buf As String
            Dim FSO2 As Object, TextFile2 As Object, buf2 As String
            Set FSO = CreateObject("Scripting.FileSystemObject")
            Set FSO2 = CreateObject("Scripting.FileSystemObject")
            Set TextFile = FSO.OpenTextFile(current_path & "/" & "R結果1_" & i & ".txt")
            Set TextFile2 = FSO2.OpenTextFile(current_path & "/" & "R結果2_" & i & ".txt")
            buf = TextFile.ReadAll
            buf2 = TextFile2.ReadAll

            Selection.InsertAfter (buf)
            Selection.EndKey unit:=wdStory
            
            picture_path = current_path & "/" & "R図_" & i & ".png"
            Selection.InlineShapes.AddPicture FileName:=picture_path
            Selection.EndKey unit:=wdStory
            
            Selection.InsertAfter (buf2)
            Selection.EndKey unit:=wdStory
        
            Set TextFile = Nothing
            Set FSO = Nothing
            
            Set TextFile2 = Nothing
            Set FSO2 = Nothing           
        
            If i < counter Then
               Selection.InsertBreak Type:=wdPageBreak
            End If
        Next i

        ActiveDocument.ExportAsFixedFormat _
        OutputFileName:=output_path, _
        ExportFormat:=wdExportFormatPDF, _
        OpenAfterExport:=True, _
        Range:=wdExportAllDocument
        
        Dim d As Integer
        For d = 1 To counter
            Kill current_path & "/" & "R結果1_" & d & ".txt"
            Kill current_path & "/" & "R結果2_" & d & ".txt"
            Kill current_path & "/" & "R図_" & d & ".png"
        Next d
        
        Application.Quit (wdDoNotSaveChanges)
End Sub

「InsertFile」を使うと文字ばけするようである。

            Selection.InsertFile FileName:=current_path & "/" & "R結果1_" & n & ".txt"

そのため以下の方法に変更したら問題なかった。

            Dim FSO As Object, TextFile As Object, buf As String
            Set FSO = CreateObject("Scripting.FileSystemObject")
            Set TextFile = FSO.OpenTextFile(current_path & "/" & "R結果1_" & i & ".txt")
            buf = TextFile.ReadAll

            Selection.InsertAfter (buf)

これでknitrを勉強しないで済むのかな?

Excelのコマンドボタンの右クリックを有効にする方法

Excel

以下の二つは共存可能。

Private Sub CommandButton1_Click()
    
    MsgBox ("左クリック")
    
End Sub

Private Sub CommandButton1_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

    If Button = 2 Then MsgBox ("右クリック")
    
End Sub

VBAでカレンダーコントロールを自作する

Excel

簡単にコピペで再現できるようにボタンなどのコントロールの配置やそのプロパティはすべてコードに記述。フォームやモジュールを追加して下記をコピペするだけで完成。

①カレンダーフォーム「Calender」を追加する

Option Explicit

Private Sub UserForm_Initialize()

    'widthとinsidewidthの差は4.5 (5*2+30*7+4.5=224.5)
    Me.Width = 224.5
    Me.Height = 285
    
End Sub

②標準モジュール「CalenderModule」を追加する

Option Explicit

Public calender_date As String

Function open_calender(ByVal text_date As String) As String
    
    Dim my_date As Date
    If (IsDate(text_date)) Then
        my_date = CDate(text_date)
    Else
        my_date = Date
    End If
    
    calender_date = text_date
    
    Load Calender
    
    Dim NewBtn(1 To 42) As Object
    Dim NewTxt As Object
    Dim NewCombo As Object
    Dim NewSpin As Object
    
    Dim days_label(0 To 6) As Object
    Dim obj1 As Object
    Dim obj2 As Object
    Dim obj3 As Object
    
    With Calender
        Set obj1 = .Controls.Add("Forms.Label.1", "year_label")
        Set obj2 = .Controls.Add("Forms.Label.1", "month_label")
        Set obj3 = .Controls.Add("Forms.Label.1", "year_month_label")
        
        With obj1
            .Height = 12
            .Width = 12
            .Font.Size = 12
            .Caption = "年"
            .Top = 21
            .Left = 90
        End With
        
        With obj2
            .Height = 12
            .Width = 12
            .Font.Size = 12
            .Caption = "月"
            .Top = 21
            .Left = 170
        End With
        
        With obj3
            .Height = 21
            .Width = 210
            .Font.Size = 16
            .Top = 55
            .Left = 5
            .SpecialEffect = fmSpecialEffectEtched
            .BackColor = RGB(255, 255, 255)
            .TextAlign = fmTextAlignCenter
        End With
        
        Dim i As Integer
        For i = 1 To 42
            Set NewBtn(i) = New ControlSetting
            Set NewBtn(i).myButton = .Controls.Add("Forms.CommandButton.1", "button" & i)
            With NewBtn(i).myButton
                .Height = 25
                .Width = 30
                .Top = 105 + ((i - 1) \ 7) * 25
                .Left = 5 + ((i - 1) Mod 7) * 30
                If (i - 1) Mod 7 = 0 Then .ForeColor = RGB(255, 0, 0)
                If (i - 1) Mod 7 = 6 Then .ForeColor = RGB(0, 0, 255)
            End With
        Next i
        
        Dim days As String
        days = "日月火水木金土"
        Dim days_i As Integer
        For days_i = 0 To 6
            Set days_label(days_i) = .Controls.Add("Forms.Label.1", "days_label" & days_i)
            With days_label(days_i)
                .Height = 18
                .Width = 30
                .Top = 87
                .Left = 5 + days_i * 30
                .Font.Size = 14
                .Font.Bold = True
                .TextAlign = fmTextAlignCenter
                .Caption = Mid(days, days_i + 1, 1)
                If days_i = 0 Then .ForeColor = RGB(255, 0, 0)
                If days_i = 6 Then .ForeColor = RGB(0, 0, 255)
            End With
        Next days_i
        
        Set NewTxt = New ControlSetting
        Set NewTxt.myTxt = .Controls.Add("Forms.TextBox.1", "year_txt")
        With NewTxt.myTxt
           .Height = 18
           .Width = 66
           .Top = 18
           .Left = 15
           .Font.Size = 12
           .TextAlign = fmTextAlignCenter
           .IMEMode = fmIMEModeDisable
           .Text = Year(my_date)
        End With
        
        Set NewCombo = New ControlSetting
        Set NewCombo.myCombo = .Controls.Add("Forms.ComboBox.1", "month_txt")
        With NewCombo.myCombo
            .Height = 18
            .Width = 48
            .Top = 18
            .Left = 115
            .Font.Size = 12
            .TextAlign = fmTextAlignCenter
            .Style = fmStyleDropDownCombo
            .ListRows = 12
             Dim month_i As Integer
             For month_i = 1 To 12
                 .AddItem month_i
             Next month_i
            .ListIndex = Month(my_date) - 1
        End With
         
        Set NewSpin = New ControlSetting
        Set NewSpin.mySpin = .Controls.Add("Forms.SpinButton.1", "updown")
        With NewSpin.mySpin
            .Height = 25.5
            .Width = 12.75
            .Top = 14
            .Left = 190
        End With
            
    End With
    
    Dim num As Integer
    Dim dd As String
    dd = Day(my_date)
    For num = 1 To 42
        If Calender.Controls("button" & num).Caption = dd And Calender.Controls("button" & num).Enabled Then
            Calender.Controls("button" & num).SetFocus
        End If
    Next num
    
    Calender.Show
    
    open_calender = calender_date
    
End Function
Function calender_hantei() As Boolean

    Dim kekka As Boolean
    
    If Not IsNumeric(Calender.Controls("year_txt").Text) Then
        kekka = False
    Else
        Calender.Controls("year_txt").Text = Int(Calender.Controls("year_txt").Text)
        kekka = True
    End If
    
    calender_hantei = kekka
  
End Function

Function calender_reload()

    Dim yy As Integer
    yy = Calender.Controls("year_txt").Text
    
    If yy < 1800 Then Exit Function
    If yy > 3000 Then Exit Function
    
    Dim button_i As Integer
    For button_i = 1 To 42
        Calender.Controls("button" & button_i).Caption = ""
        Calender.Controls("button" & button_i).Font.Size = 10
        Calender.Controls("button" & button_i).Enabled = False
    Next button_i
    
    Dim mm As Integer
    Dim d As Date
    Dim start_position As Integer
    Dim end_day As Integer
    
    yy = Calender.Controls("year_txt").Text
    mm = Calender.Controls("month_txt").Text
    Calender.Controls("year_month_label").Caption = yy & "年" & mm & "月"
    
    d = yy & "/" & mm & "/" & 1
    start_position = Weekday(d)

    Dim days_number As Integer '何日あるか
    days_number = Day(DateSerial(yy, mm + 1, 0))
    
    Dim start_day As Date
    start_day = d - (start_position - 1)
    Dim index As Integer
    For index = 1 To 42
        Calender.Controls("button" & index).Caption = Day(start_day + index - 1)
        If Month(start_day + index - 1) = mm Then
            Calender.Controls("button" & index).Font.Size = 12
            Calender.Controls("button" & index).Enabled = True
        End If
    Next index
        
End Function

③クラスモジュール「ControlSetting」を追加する

Option Explicit

Public WithEvents myButton As CommandButton
Public WithEvents myTxt As MSForms.TextBox
Public WithEvents myCombo As MSForms.ComboBox
Public WithEvents mySpin As MSForms.SpinButton

Private Sub myButton_Click()

    calender_date = Calender.Controls("year_month_label").Caption & myButton.Caption & "日"

    Unload Calender    

End Sub

Private Sub myTxt_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
     
    If KeyCode = vbKeyReturn Then
        Dim hantei As Boolean
        hantei = calender_hantei
        If Not (hantei) Then Exit Sub
        
        Call calender_reload
    End If

End Sub

Private Sub myCombo_Change()
    
    If Not (Me.myCombo.MatchFound) Then Exit Sub
    
    Dim hantei As Boolean
    hantei = calender_hantei
    If Not (hantei) Then Exit Sub
    
    Call calender_reload
    
End Sub

Private Sub mySpin_SpinDown()
    
    Dim hantei As Boolean
    hantei = calender_hantei
    If Not (hantei) Then Exit Sub
    
    Dim index As String
    index = Calender.Controls("month_txt").ListIndex
    If (index = -1) Then Exit Sub
    If (index = 0) Then
        Calender.Controls("year_txt").Text = Calender.Controls("year_txt").Text - 1
        index = 11
    Else
        index = index - 1
    End If
    Calender.Controls("month_txt").ListIndex = index
    
End Sub

Private Sub mySpin_SpinUp()

    Dim hantei As Boolean
    hantei = calender_hantei
    If Not (hantei) Then Exit Sub
    
    Dim index As String
    index = Calender.Controls("month_txt").ListIndex
    If (index = 11) Then
        Calender.Controls("year_txt").Text = Calender.Controls("year_txt").Text + 1
        index = 0
    Else
        index = index + 1
    End If
    Calender.Controls("month_txt").ListIndex = index
    
End Sub

使い方は、例としてテキストボックス「TextBox1」とコマンドボタン「CommandButton1」がセットされているユーザーフォームで

Private Sub CommandButton1_Click()

    TextBox1.Text = open_calender(TextBox1.Text)
    
End Sub