2019年1月11日 星期五

Unity c# read Xml

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;

public class ReadXml : MonoBehaviour {

 Hashtable ht = new Hashtable();
 string filePath = @"C:\Users\JohnLin\Desktop\CKIP\xmlcorpus_004.xml";

 XmlDocument xmlDocument = new XmlDocument();

 int sentenceLenght = 0;

 private void Start() {
  
  xmlDocument.Load(filePath);
  XmlNodeList genre = xmlDocument.SelectNodes("//genre"); 

  senterce();
 } 

 ///
 ///xml 句子
 ///
 private void senterce (){
  
  XmlNodeList topM = xmlDocument.SelectNodes("//text");  // 節點

  foreach (XmlElement elements in topM)
  {
   while(true){
    if(elements.GetElementsByTagName("sentence")[sentenceLenght] != null){ //  sentence 節點
     Debug.Log(elements.GetElementsByTagName("sentence")[sentenceLenght].InnerText);
     break;
    }
   }
  }
 }
}


------- XML -------

<corpus>
    <article>
        <genre>散文</genre>
        <style>記敘</style>
        <mode>written</mode>
        <topic>其他文學創作</topic>
        <medium>視聽媒體</medium>
        <author>
            <name>周文仁</name>
            <sex>男</sex>
            <nationality>中華民國</nationality>
            <nativelang>中文</nativelang>
        </author>
        <publisher />
        <publishlocation />
        <publishdate>1994</publishdate>
        <edition />
        <title />
        <text>
            <sentence>生活(Na) 不過(Cbb) 就(D) 是(SHI) 一個個(Neqa) 的(DE) 
        </text>
    </article>
</corpus>

------結果圖------

2019年1月1日 星期二

長詞優先法與詞位標籤-更新版(更新版)

----MySQL Script(語料庫)------
using System.Collections.Generic;
using System.Data;
using System;
using MySql.Data.MySqlClient;
using System.Text;

namespace MySQL
{
    public class MySQL
    {
        public static MySqlConnection mySqlConnection;

        // DataBase Ip;
        private static string HOST = "163.15.198.171";
        public static string HOST_TYPE
        {
            set { HOST = value; }
            get { return HOST; }
        }

        // DataBase user Id
        private static string ID = "gsp40213";
        public static string ID_TYPE
        {
            set { ID = value; }
            get { return ID; }
        }

        // DataBase password
        private static string PASSWORD = "******";
        public static string PASSWORD_TYPE
        {
            set { PASSWORD = value; }
            get { return PASSWORD; }
        }

        // DataBase Name
        private static string DATABASE = "corpus2";
        public static string DATABASE_TYPE
        {
            set { DATABASE = value; }
            get { return DATABASE; }
        }

        private static string PORT = "****";
        public static string PORT_TYPE
        {
            set { PORT = value; }
            get { return PORT; }
        }

        // 連線結果
        public static string RESULT = "";

        //  Connect to SQL
        public static void OpenSqlConnection(string connction)
        {
            try
            {
                mySqlConnection = new MySqlConnection(connction);
                mySqlConnection.Open();
                RESULT = mySqlConnection.ServerVersion;
            }
            catch
            {
                RESULT = "無法連接資料庫";
            }
        }

        // Close Sql
        public static void closeSqlConnection()
        {
            mySqlConnection.Close();
            mySqlConnection.Dispose();
            mySqlConnection = null;
        }

        // SQL Query
        public static void DOQUERY(string sqlQuery)
        {
            IDbCommand dbcommand = mySqlConnection.CreateCommand();
            dbcommand.CommandText = sqlQuery;
            IDataReader reader = dbcommand.ExecuteReader();
            reader.Close();
            reader = null;
            dbcommand.Dispose();
            dbcommand = null;
        }

        // Get DataSet
        public static DataSet GetDataSet(string sqlString)
        {
            DataSet ds = new DataSet();

            try
            {
                MySqlDataAdapter da = new MySqlDataAdapter(sqlString, mySqlConnection);
            }
            catch (Exception e)
            {
                throw new Exception("SQL:" + sqlString + "\n");
            }
            return ds;
        }

        /// 
        /// string to uft8
        /// message: sentence
        /// 
        /// 
        /// 
        public static string STRING_UTF8(string message)
        {
            UTF8Encoding encoder = new UTF8Encoding();
            byte[] bytes = Encoding.UTF8.GetBytes(message);
            string utf8ReturenString = encoder.GetString(bytes);

            return utf8ReturenString;
        }

        /// 
        /// INQUIRE_DATABASE
        ///  * dataBaseTitle : DataBaseName 
        ///  * dataBaseTitle : DataBaseName 
        ///  * numberingType : 0(Message)、1(Words)、2(Mark)、3(Words2)、4(Mark2)、5(Lexical) 
        ///  * message: message 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static string INQUIRE_DATABASE(string dataBaseTitle, int numberingType, string message)
        {
            string sqlText = "select * from " + dataBaseTitle + " where Message='" + message + "'";

            string str = "";
        
            MySqlCommand cmd = new MySqlCommand(sqlText, mySqlConnection);
            MySqlDataReader data = cmd.ExecuteReader();

            while (data.Read())
            {
                try
                {
                    str = data[numberingType].ToString();
                }
                finally { }
            }
            data.Close();

            return str;
        }

        /// 
        /// 詞性標記顯示
        /// words: dataBase table[1]
        /// 
        /// 
        /// 
        public static string wordsMark(string words)
        {
            string str = "";

            switch (words.ToString())
            {
                case "A":
                    str = "非謂形容詞";
                    break;
                case "Caa":
                    str = "對等連接詞";
                    break;
                case "Cab":
                    str = "連接詞";
                    break;
                case "Cba":
                    str = "連接詞";
                    break;
                case "Cbb":
                    str = "關聯連接詞";
                    break;
                case "Da":
                    str = "數量副詞";
                    break;
                case "Dfa":
                    str = "動詞前副詞";
                    break;
                case "Dfb":
                    str = "動詞後副詞";
                    break;
                case "Di":
                    str = "時態標記";
                    break;
                case "Dk":
                    str = "句副詞";
                    break;
                case "D":
                    str = "副詞";
                    break;
                case "Na":
                    str = "普通名詞";
                    break;
                case "Nb":
                    str = "專有名詞";
                    break;
                case "Nc":
                    str = "地方詞";
                    break;
                case "Ncd":
                    str = "位置詞";
                    break;
                case "Nd":
                    str = "時間詞";
                    break;
                case "Neu":
                    str = "數量定詞";
                    break;
                case "Nes":
                    str = "特指定詞";
                    break;
                case "Nep":
                    str = "指代定詞";
                    break;
                case "Neqa":
                    str = "數量定詞";
                    break;
                case "Neqb":
                    str = "數量定詞(後置)";
                    break;
                case "Nf":
                    str = "量詞";
                    break;
                case "Ng":
                    str = "後置詞";
                    break;
                case "Nh":
                    str = "代名詞";
                    break;
                case "Nv":
                    str = "名物化動詞";
                    break;
                case "I":
                    str = "感嘆詞";
                    break;
                case "P":
                    str = "介詞";
                    break;
                case "T":
                    str = "語助詞";
                    break;
                case "VA":
                    str = "動作不及物動詞";
                    break;
                case "VAC":
                    str = "動作使動動詞";
                    break;
                case "VB":
                    str = "動作類及物動詞";
                    break;
                case "VC":
                    str = "動作及物動詞";
                    break;
                case "VCL":
                    str = "動作接地方賓語動詞";
                    break;
                case "VD":
                    str = "雙賓動詞";
                    break;
                case "VE":
                    str = "動作句賓動詞";
                    break;
                case "VF":
                    str = "動作謂賓動詞";
                    break;
                case "VG":
                    str = "分類動詞";
                    break;
                case "VH":
                    str = "狀態不及物動詞";
                    break;
                case "VHC":
                    str = "狀態使動動詞";
                    break;
                case "VI":
                    str = "狀態類及物動詞";
                    break;
                case "VJ":
                    str = "狀態及物動詞";
                    break;
                case "VK":
                    str = "狀態句賓動詞";
                    break;
                case "VL":
                    str = "狀態謂賓動詞";
                    break;
                case "V_2":
                    str = "不及物連接動詞";
                    break;
                case "DE":
                    str = "狀態感嘆詞";
                    break;
                case "SHI":
                    str = "不及物狀態動詞";
                    break;
                case "FW":
                    str = "外文";
                    break;
                case "COMMACATEGORY":
                    str = "逗號";
                    break;
                case "DASHCATEGORY":
                    str = "破折號";
                    break;
                case "ETCCATEGORY":
                    str = "刪節號";
                    break;
                case "EXCLAMATIONCATEGORY":
                    str = "感嘆號";
                    break;
                case "PARENTHESISCATEGORY":
                    str = "括號";
                    break;
                case "PAUSECATEGORY":
                    str = "頓號";
                    break;
                case "PERIODCATEGORY":
                    str = "句號";
                    break;
                case "QUESTIONCATEGORY":
                    str = "問號";
                    break;
                case "SEMICOLONCATEGORY":
                    str = "分號";
                    break;
                case "SPCHANGECATEGORY":
                    str = "雙直號";
                    break;
            }
            return str;
        }
    }
}


---------SegmentationSymbolTool Script (斷字功能)----------
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace SegmentationSymbolTool
{
    public class SegmentationSymbol2
    {
        // 斷詞標記括號
        private string[] specialSymbol = new string[] { "(", ")" };
        // 斷字狀態
        private string statusBroken;

        // 刪除特殊符號
        public string delectSymbol(string userMessage)
        {
            string strs = userMessage;

            for (int x = 0; x < specialSymbol.Length; x++)
                strs = strs.Replace(specialSymbol[x], " ");

            return strs;
        }

        /// 
        /// 斷字字數
        ///  status: sentence Lenght 
        /// 
        /// 
        private void status_conter(int status)
        {
            statusBroken = "";

            for (int x = 0; x <= status; x++)
                statusBroken += @"\S";
        }

        /// 
        /// 刪除訊息
        /// message: sentence
        /// status: Hyphenation state
        /// 
        /// 
        /// 
        /// 
        public string delectWord(string message, int status)
        {
            string str = message;

            return str.Remove(status).ToString();
        }

        /// 
        /// 斷字狀態
        /// message: sentence
        /// status: Hyphenation state
        /// 
        /// 
        /// 
        /// 
        public List brokenSatus(string message, int status)
        {
            status_conter(status);

            List match = new List();
            MatchCollection splitResult = Regex.Matches(message, statusBroken, RegexOptions.IgnoreCase);

            foreach (Match test in splitResult)
                match.Add(test);

            return match;
        }

        /// 
        /// 組合處理
        /// message: sentence
        /// int: Hyphenation state
        /// 
        /// 
        /// 
        /// 
        public List delect_Word_Combination(string message, int status)
        {
            status_conter(status);

            string str = message;
            List match = new List();
            List stringList = new List();

            MatchCollection splitResult = Regex.Matches(str, statusBroken, RegexOptions.IgnoreCase);
            foreach (Match test in splitResult)
                match.Add(test.ToString());
            foreach (string strs in match)
            {
                stringList.Add(str.Replace(strs, ""));

                return stringList;
            }

            return stringList;
        }

        /// 
        /// 斷字處理
        /// message: sentence
        /// status: Hyphenation state
        /// 
        /// 
        /// 
        /// 
        public List delect_oneWord(string message, int status)
        {
            status_conter(status);

            string str = message;
            List match = new List();
            List stringList = new List();

            MatchCollection splitResult = Regex.Matches(str, statusBroken, RegexOptions.IgnoreCase);
            foreach (Match test in splitResult)
                match.Add(test.ToString());
            foreach (string strs in match)
                stringList.Add(str.Replace(strs, ""));

            return stringList;
        }
    }
}


------LongWordsFirst2 Scrit (長詞優先法)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text.RegularExpressions;
using System;

public class LongWordsFirst2 : MonoBehaviour
{
    // 斷詞工具
    private SegmentationSymbolTool.SegmentationSymbol2 segmentationSybolTool = new SegmentationSymbolTool.SegmentationSymbol2();

    // 斷字系統資料表
    private static string dataBasetitle = "glossary";

    // 顯示結果
    private string resultMessage;
    public string resultMessageType
    {
        get { return resultMessage; }
    }

    // 使用者輸入句子
    private string message = "";
    public  string messageType
    {
        set { message = value; }
        get { return message; }
    }

    // 正向長詞優先
    public string logeWordForward;

    // 反向長詞優先
    public string logeWordReverse;
    public string logeWordReverseType
    {
        get { return logeWordReverse; }
    }

    // 正向長詞優先長度, 反向長詞優先長度, 組合長度
    private int logeWordForwadLenght, logeWordReverseLenght;

    // 正向長詞優先結果
    private List logeWordForwardFunctionList = new List();
    public List logeWordForwardFunctionListType
    {
        get { return logeWordForwardFunctionList; }
    }

    // 反向長詞優先結果
    private List logeWordReverseFunctuinList = new List();

    // 正向長詞優先標記結果
    private List logeWordForwardLexicalFunctionList = new List();
    public List logeWordForwardLexicalFunctionListType
    {
        get { return logeWordForwardLexicalFunctionList; }
    }

    // 反向長詞優先結果
    public List logeWordReverseLexicalFunctionList = new List();
    public List logeWordReverseLexicalFunctionListType
    {
        get { return logeWordReverseLexicalFunctionList; }
    }

    // 反向長詞方向校正結果
    public List logeWordReverseCorrectionList = new List();
    public List logeWordReverseCorrectionListType
    {
        get { return logeWordReverseCorrectionList; }
    }

    // 正向長詞優先詞性變化1
    private List logeWordForwardMark1List = new List();
    public List logeWordForwardMark1Type
    {
        get { return logeWordForwardMark1List; }
    }

    // 反向長詞優先詞性變化1
    private List logeWordReverseMark1List = new List();
    public List logeWordReverseMark1Tpye
    {
        get { return logeWordReverseMark1List; }
    }

    // 打開資料庫
    public void OpenDataBase()
    {
        string connectionString = string.Format("Server = {0}; Database = {1}; UserID = {2}; Password = {3}; Port = {4};", MySQL.MySQL.HOST_TYPE, MySQL.MySQL.DATABASE_TYPE, MySQL.MySQL.ID_TYPE, MySQL.MySQL.PASSWORD_TYPE, MySQL.MySQL.PORT_TYPE);
        MySQL.MySQL.OpenSqlConnection(connectionString);
    }

    /// 
    /// 關閉資料庫
    /// 
    public void closeDataBase()
    {
        MySQL.MySQL.closeSqlConnection();
    }

    /// 
    /// 切字準備
    /// 優先執行
    /// 
    public void cuttingReady()
    {
        logeWordForward = message;
        logeWordReverse = message;

        logeWordForwadLenght = logeWordForward.Length;
        logeWordReverseLenght = logeWordReverse.Length;
       
        // 清除List
        logeWordForwardFunctionList.Clear();
        logeWordReverseFunctuinList.Clear();
        logeWordForwardLexicalFunctionList.Clear();
        logeWordReverseLexicalFunctionList.Clear();
        logeWordReverseCorrectionList.Clear();
        logeWordForwardMark1List.Clear();
        logeWordReverseMark1List.Clear();
      
        // 執行正向長詞優先
        StartCoroutine(loneWordForwardFunction());

        // 執行反向長詞優先
        StartCoroutine(longWordReverseFunction(0));

        // 正向長詞優先詞位標記
        StartCoroutine(logeWordForwardLexicalFunction(logeWordForwardFunctionList, logeWordForwardLexicalFunctionList));

        // 反向長詞優先方校校正
        StartCoroutine(logeWordReverseCorrectionFunction());

        // 反向長詞優先詞位標記
        StartCoroutine(logeWordForwardLexicalFunction(logeWordReverseCorrectionList, logeWordReverseLexicalFunctionList));

        // 正向長詞優先詞性變化1
        StartCoroutine(logeMakesFunction());
    }

    /// 
    /// 檢查沒有數據
    /// Message: contence
    /// Database No Data
    /// 
    /// 
    /// 
    /// 
    private string inspection(string message, List list)
    {
        string str = message;

        foreach (string str1 in list)
        {
            str = str.Replace(str1, "");
        }

        return str;
    }

    /// 
    /// 反向長詞優先校正
    /// 
    IEnumerator logeWordReverseCorrectionFunction()
    {
        while (true)
        {
            if (logeWordReverse.Equals(""))
            {
                for (int x = logeWordReverseFunctuinList.Count-1; x >= 0; x--)
                    logeWordReverseCorrectionList.Add(logeWordReverseFunctuinList[x]);
                break;
            }

            yield return new WaitForSeconds(0.5f);
        }
    }

    /// 
    /// 詞位標籤
    /// longWord: positive longWord / reverse longWord
    /// LexicalResult: positive longWord Result / reverse longWord Result
    /// 
    /// 
    /// 
    /// 
    IEnumerator logeWordForwardLexicalFunction(List longWord, List LexicalResult)
    {
        int number = 0;

        while (true)
        {
            if (logeWordForward.Equals(""))
            {
                foreach (string str in longWord)
                {
                    LexicalResult.Add(MySQL.MySQL.INQUIRE_DATABASE(dataBasetitle, 5, str));
                    number += 1;
                }

                // 限制迴圈執行
                if (number <= longWord.Count)
                    break;
            }

            yield return new WaitForSeconds(0.5f);
        }
    }

    /// 
    /// 正向長詞優先
    /// IEnumerator: unity執行序
    /// 
    /// 
    IEnumerator loneWordForwardFunction()
    {
        while (true)
        {
            foreach (Match match in segmentationSybolTool.brokenSatus(logeWordForward, logeWordForwadLenght))
            {
                if (match.ToString() == MySQL.MySQL.INQUIRE_DATABASE(dataBasetitle, 0, match.ToString()))
                {
                    logeWordForwardFunctionList.Add(match.ToString());

                    logeWordForward = inspection(logeWordForward, logeWordForwardFunctionList);
                    logeWordForwadLenght = logeWordForward.Length;
                }
            }

            if (logeWordForwadLenght <= 0)
                logeWordForwadLenght = 0;
            else logeWordForwadLenght -= 1;

            yield return new WaitForSeconds(0.5f);
        }
    }

    /// 
    /// 後向長詞優先
    /// lenght: sentence lenght
    /// IEnumerator: unity 執行序
    /// 
    /// 
    /// 
    IEnumerator longWordReverseFunction(int lenght)
    {
        while (true)
        {
            foreach (Match match in segmentationSybolTool.brokenSatus(logeWordReverse, logeWordReverse.Length))
            {
                if (match.ToString() == MySQL.MySQL.INQUIRE_DATABASE(dataBasetitle, 0, match.ToString()))
                {
                    logeWordReverseFunctuinList.Add(match.ToString());
                    logeWordReverse = segmentationSybolTool.delectWord(logeWordReverse, match.Length);
                }
            }

            try
            {
                foreach (string str in segmentationSybolTool.delect_Word_Combination(logeWordReverse, lenght))
                {
                    if (str == MySQL.MySQL.INQUIRE_DATABASE(dataBasetitle, 0, str))
                    {
                        logeWordReverseFunctuinList.Add(str);
                        lenght = 0;
                        logeWordReverse = segmentationSybolTool.delectWord(logeWordReverse, logeWordReverse.Length - str.Length);
                    }
                }
                lenght += 1;

                if (logeWordReverse == MySQL.MySQL.INQUIRE_DATABASE(dataBasetitle, 0, logeWordReverse))
                {
                    logeWordReverseFunctuinList.Add(logeWordReverse);
                    logeWordReverse = segmentationSybolTool.delectWord(logeWordReverse, logeWordReverse.Length - MySQL.MySQL.INQUIRE_DATABASE(dataBasetitle, 0, logeWordReverse).Length);
                }

                if (lenght >= logeWordReverseLenght)
                    lenght = 0;

            }
            catch (Exception e) { logeWordReverseFunctuinList.Remove("");}

            yield return new WaitForSeconds(0.5f);

        }
    }

    /// 
    /// logeMakesFunction
    /// Variety1 and Variety2
    /// 
    /// 
    IEnumerator logeMakesFunction()
    {
        while (true)
        {
            if (logeWordForward.Equals(""))
            {
                // 正向長詞優先詞性變化1
                foreach (string str in logeWordForwardFunctionList)
                    logeWordForwardMark1List.Add(MySQL.MySQL.INQUIRE_DATABASE(dataBasetitle, 2, str));

                // 反向長詞優先詞性變化1
                foreach(string str in logeWordReverseCorrectionList)
                    logeWordReverseMark1List.Add(MySQL.MySQL.INQUIRE_DATABASE(dataBasetitle, 2, str));
                break;
            }
            yield return new WaitForSeconds(0.5f);
        }
    }

    /// 
    /// result Systematics
    /// 
    /// 
    public IEnumerator logWordResultSystematics()
    {
        string logeWordForwardMessage = "", logeWordReverseMessage = "";
        string logeWordForward_LexicalMessage = "", logeWordReverse_LexicalMessage = "";


        while (true)
        {
            if (logeWordForward.Equals(""))
            {
                for (int x = 0; x <= logeWordForwardFunctionList.Count - 1; x++)
                    logeWordForwardMessage += logeWordForwardFunctionList[x] + "(" + logeWordForwardMark1List[x] + ")" + " ";

                for (int x = 0; x <= logeWordReverseCorrectionList.Count - 1; x++)
                    logeWordReverseMessage += logeWordReverseCorrectionList[x] + "(" + logeWordReverseMark1List[x] + ")" + " ";
                
                foreach (string str in logeWordForwardLexicalFunctionList)
                    logeWordForward_LexicalMessage += str + "|";

                foreach (string str in logeWordReverseLexicalFunctionList)
                    logeWordReverse_LexicalMessage += str + "|";

                resultMessage = "正向長詞優先結果: \n" + logeWordForwardMessage + "\n\n" + "反向長詞優先結果: \n" + logeWordReverseMessage + "\n\n"
                    + "正向長詞詞位標記: \n" + logeWordForward_LexicalMessage + "\n\n" + "反向長詞詞位標記: \n" + logeWordReverse_LexicalMessage;

                break;
            }
            yield return new WaitForSeconds(0.5f);
        }
    }
}


-----Layout Script (介面)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Layout : LongWordsFirst2 {

    public Text systemMessage, inputMessage, result, runStatus;
    public InputField userField;
    public Button buttonEnter;
    public Button buttonRefill;
    public Button exit;
    public Image inputMessageBackground;
    public Button Sort;

    // 顯示文字結果
    public Text resultText;
    public Scrollbar scrollbarResult;

    /// 
    /// 確定
    /// 
    void btnOnClick_Enter()
    {
        cuttingReady();
    }

    /// 
    /// 重填
    /// 
    void btnOnClick_Refill()
    {
        inputFieldType(userField, 0.6f, 1, 1, 1).text = "";
        messageType = "";
    }

    /// 
    /// 顯示結果
    /// 
    void btnOnClick_Sort()
    {
        try
        {
            if (logeWordReverseType.Length == 0)
            {
                textType(runStatus, "(等待執行)", 25, Color.blue, 0.6f, 1.8f); // title
                StartCoroutine(logWordResultSystematics());
                resultTextType(resultText).text = resultMessageType; // display result Message
            }

            else
            {
                textType(runStatus, "(執行)", 25, Color.blue, 0.6f, 1.8f);
            }
        }
        catch { }
    }

    /// 
    /// 離開應用程式
    /// 
    void btnOnClick_Exit()
    {
        Application.Quit();
        MySQL.MySQL.closeSqlConnection();
    }

    /// 
    /// button Component
    /// btn: button Obj
    /// width / height: button Obj posistion
    /// sizeX / sizeY: button Obj size
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    Button buttonType(Button btn, float width, float height, float sizeX, float sizeY)
    {
        try
        {
            btn.transform.position = new Vector2(Screen.width / 2 * width, Screen.height / 2 * height);
            // posistion
            btn.transform.position = new Vector2(Screen.width / 2 * width, Screen.height / 2 * height);
            // imageSize
            btn.image.rectTransform.sizeDelta = new Vector2(Screen.width / 2 * sizeX, sizeY);

            switch (btn.name)
            {
                case "Enter":
                    btn.onClick.AddListener(() => btnOnClick_Enter());
                    break;
                case "Refill":
                    btn.onClick.AddListener(() => btnOnClick_Refill());
                    break;
                case "Exit":
                    btn.onClick.AddListener(() => btnOnClick_Exit());
                    break;
                case "Sort":
                    btn.onClick.AddListener(() => btnOnClick_Sort());
                    break;

            }
        }
        catch { }

        return btn;
    }

    /// 
    /// inputField Component
    /// InputField: inputField Obj
    /// message: sentence message
    /// width / height: inputField Obj posistion
    /// sizeX / sizeY: inputField size
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    InputField inputFieldType(InputField inputField,float width, float height, float sizeX, float sizeY)
    {
        inputField.transform.position = new Vector2(Screen.width / 2 * width, Screen.height / 2 * height);
        inputField.image.rectTransform.sizeDelta = new Vector2(Screen.width / 2 * sizeX, Screen.height / 2 * sizeY);

        return inputField;
    }

    /// 
    /// scrollbarType
    /// Scrollbar: scrollbar obj
    /// width / height: scrollbar obj posistion
    /// sizeX / sizeY: scrollbar obj size
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    Scrollbar scrollbarType(Scrollbar scrollbar, float width, float height)
    {
        try
        {
            scrollbar.transform.position = new Vector2(Screen.width / 2 * width, Screen.height / 2 * height);
        }
        catch { }

        return scrollbar;
    }

    // Text 屬性
    Text textType(Text text, string message, int fontsize, Color color, float width, float height)
    {
        try
        {
            Color col = new Color(color.r, color.g, color.b);

            // posistion 
            text.rectTransform.position = new Vector2(Screen.width / 2 * width, Screen.height / 2 * height);

            text.text = message;
            text.fontSize = fontsize;
            text.color = col;
        }
        catch { }
        return text;
    }

    /// 
    /// ImageType
    /// Image: image obj
    /// width / height: image obj posistion
    /// sizeX / sizeY: image obj size
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    /// 
    Image ImageType(Image image, float width, float height, float sizeX, float sizeY)
    {
        try
        {
            // posistion
            image.rectTransform.position = new Vector2(Screen.width / 2 * width, Screen.height / 2 * height);

            // imageSize
            image.rectTransform.sizeDelta = new Vector2(Screen.width / 2 * sizeX, Screen.height / 2 * sizeY);
        }
        catch { }

        return image;
    }

    /// 
    /// resultTextType
    /// 
    /// 
    /// 
    Text resultTextType(Text text)
    {
        try
        {
            text.horizontalOverflow = HorizontalWrapMode.Wrap;
            text.verticalOverflow = VerticalWrapMode.Overflow;
        }
        catch { }

        return text;
    }

    void Start()
    {
        OpenDataBase(); // openDatabase

        textType(systemMessage, "歡迎使用系統", 25, Color.red, 0.3f, 1.8f); // title
        textType(inputMessage,"請輸入句子", 25, Color.red, 0.3f, 1.6f); // title

        buttonType(buttonEnter, 0.2f, 0.3f, 0.2f, 30); // enter button
        buttonType(buttonRefill, 0.6f, 0.3f, 0.2f, 30); // return input Message button
        buttonType(exit, 1f, 0.3f, 0.2f, 30); // exit button
        buttonType(Sort, 0.4f, 0.3f, 0.2f, 30); // sort button

        textType(result, "結果", 25, Color.red, 1.4f, 1.8f); // result
    }

    void Update()
    {
        messageType = inputFieldType(userField, 0.6f, 1, 1, 1).text; // user input Message
        ImageType(inputMessageBackground, 1.55f, 1.1f, 0.8f, 1.2f); // result background
        scrollbarType(scrollbarResult, 1.93f, 1.1f);
    }
}

專案下載
------ 結果圖-----

2018年12月18日 星期二

物件跟隨

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PetFlow : MonoBehaviour {

    public Transform player;
    public float maxDis = 5;

    private SmoothFollowerObj posFollow; // 控制位置平滑移動
    private SmoothFollowerObj lookFollow; // 控制朝向平滑轉換

    public Vector3 posistionVector; // 角色位置移動,方向向量
    public Vector3 lookVector; //角色朝向變化,朝向向量

    private Vector3 lastVelocityDir; // 上一次移動方向
    private Vector3 lastPost; // 之前移動目標位置

    void Start()
    {
        posFollow = new SmoothFollowerObj(0.5f, 0.5f);
        lookFollow = new SmoothFollowerObj(0.1f, 0.1f);
        posFollow.Update(transform.position, 0, true); // 初始位置
        lookFollow.Update(player.transform.position, 0, true);

        posistionVector = new Vector3(0, 0.5f, 1.7f);
        lookVector = new Vector3(0, 0, 1.5f);

        lastVelocityDir = player.transform.forward;
        lastPost = player.transform.position;
    }

    void Update()
    {
        float dis = Vector3.Distance(transform.position, player.position);

        if (dis > maxDis)
            PetMoveFlow();
    }

    // 物件移動
    void PetMoveFlow()
    {
        lastVelocityDir += (player.position - lastPost) * 5;
        lastPost = player.position;

        lastVelocityDir += player.transform.forward * Time.deltaTime;
        lastVelocityDir = lastVelocityDir.normalized;

        Vector3 horizontal = transform.position - player.position;
        Vector3 horizontal2 = horizontal;
        Vector3 vertical = player.up;
        Vector3.OrthoNormalize(ref vertical, ref horizontal);  // https://docs.unity3d.com/ScriptReference/Vector3.OrthoNormalize.html api

        // https://docs.unity3d.com/ScriptReference/Vector3-sqrMagnitude.html api
        if (horizontal.sqrMagnitude > horizontal2.sqrMagnitude)
            horizontal = horizontal2;

        transform.position = posFollow.Update(player.position + horizontal * Mathf.Abs(posistionVector.z)
            + vertical * posistionVector.y, Time.deltaTime);

        horizontal = lastVelocityDir;

        Vector3 look = lookFollow.Update(player.position + horizontal * lookVector.z
            - vertical * lookVector.y, Time.deltaTime);

        // https://docs.unity3d.com/ScriptReference/Quaternion.FromToRotation.html api
        transform.rotation = Quaternion.FromToRotation(transform.forward, look - transform.position) * transform.rotation;
    }
}

class SmoothFollowerObj
{
    private Vector3 targetPosistion; // 目標位置
    private Vector3 position; // 位置
    private Vector3 velocity;  // 速率
    private float smoothingTime; // 平滑時間
    private float prediction; // 預測

    public SmoothFollowerObj(float smoothingTime)
    {
        targetPosistion = Vector3.zero;
        position = Vector3.zero;
        this.smoothingTime = smoothingTime;
        prediction = 1;
    }

    public SmoothFollowerObj(float smoothingTime, float prediction)
    {
        targetPosistion = Vector3.zero;
        position = Vector3.zero;
        this.smoothingTime = smoothingTime;
        this.velocity = velocity;
    }

    // 更新位置資訊
    public Vector3 Update(Vector3 targetPosistionNew, float dataTime)
    {
        Vector3 targetvelocity = (targetPosistionNew - targetPosistion) / dataTime; // 獲取目標移動的方向向量
        targetPosistion = targetPosistionNew;

        float d = Mathf.Min(1, dataTime / smoothingTime);
        velocity = velocity * (1 - d) + (targetPosistion + targetvelocity * prediction - position) * d;

        position += velocity * Time.deltaTime;
        return position;
    }

    // 根據傳輸進來數據, 重置本地參數
    public Vector3 Update(Vector3 targetPosistionNew, float dataTime, bool rest) 
    {
        if (rest)
        {
            targetPosistion = targetPosistionNew;
            position = targetPosistionNew;
            velocity = Vector3.zero;

            return position;
        }

        return Update(targetPosistionNew, dataTime);
    }

    public Vector3 GetPosistion() { return position; }
    public Vector3 GetVelocity() { return velocity; }
}

物件跟隨路徑: 

程式碼來源: https://blog.csdn.net/BIGMAD/article/details/71698310

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EditorPathScript : MonoBehaviour {

    public Color rayColor = Color.red;
    public List path_objs = new List();
    Transform[] theArray;

    void OnDrawGizmos(){
        Gizmos.color = rayColor;
        theArray = GetComponentsInChildren();
        path_objs.Clear();
        foreach(Transform path_obj in theArray){
            if(path_obj != this.transform)
                path_objs.Add(path_obj);
        }

        for(int i = 0;i0){
                Vector3 previous = path_objs[i-1].position;
                Gizmos.DrawLine(previous,position);
                Gizmos.DrawWireSphere(position, 0.3f);
            }
        }
    }
}

























using UnityEngine;
using System.Collections;

public class FollowPath : MonoBehaviour {

    public bool StartFollow = false;
    public EditorPathScript PathToFollow;
    public int CurrentWayPointID = 0;
    public float Speed;//移动速度
    public float reachDistance = 0f;//里路径点的最大范围
    public string PathName;//跟随路径的名字
    private string LastName;
    private bool ChangePath = true;



    void Start () {

    }

    void Update () {
        if (!StartFollow)
            return;
        if (ChangePath)
        {
            PathToFollow = GameObject.Find(PathName).GetComponent();
            ChangePath = false;
        }
        if (LastName != PathName)
        {
            ChangePath = true;
        }
        LastName = PathName;




        float distance = Vector3.Distance(PathToFollow.path_objs[CurrentWayPointID].position, transform.position);
        //transform.Translate(PathToFollow.path_objs[CurrentWayPointID].position * Time.deltaTime * Speed, Space.Self);
        transform.position = Vector3.MoveTowards(transform.position, PathToFollow.path_objs[CurrentWayPointID].position, Time.deltaTime * Speed);
        if (distance <= reachDistance)
        {
            CurrentWayPointID++;
        }
        if (CurrentWayPointID >= PathToFollow.path_objs.Count)
        {
            CurrentWayPointID = 0;
        }
    }
}


2018年11月25日 星期日

龍捲風 物理

Tornado_Main Script (C#):

using UnityEngine;
using System.Collections;

public class Tornado_Main : MonoBehaviour {

    [Tooltip("This controls the radius of your tornados pull range")]
    public float radius = 65.28f;
    public float maxRadiusToPullIn = 10;
    [Tooltip("NEGATIVE NUMBERS ONLY. This pulls objects into the tornado")]
    public float PullingInPower = -70;
    public float MaxPullingIn = 20;

    Collider[] colliders;

    void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(transform.position, radius);
    }
    
    void Update()
    {
        colliders = Physics.OverlapSphere(transform.position, radius);
        foreach (Collider c in colliders)
        {
            if (c.GetComponent<rigidbody>() == null)
            {
                continue;
            }
            Ray ray = new Ray(transform.position, c.transform.position - transform.position);
            RaycastHit hit;
            Physics.Raycast(ray, out hit);
            if (hit.collider.name != c.gameObject.name || hit.distance &lt; MaxPullingIn)
            {
                continue;
            }
            else
            {
                Rigidbody rigidbody = c.GetComponent<rigidbody>();
                rigidbody.AddExplosionForce(PullingInPower, transform.position, radius);
            }
        }
    }
}

Outer_Tornado Script(c#):

using UnityEngine;
using System.Collections;

public class Outer_Tornado : MonoBehaviour
{

    public float radius = 19.48f;
    public float outsideSpeed = 0.7f;
    public float maxPullInLength = 24.96f;
    public float power = 1;


    Collider[] colliders;

    void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(transform.position, radius);
    }

    void Update ()
    {
        transform.RotateAround(transform.parent.transform.position, Vector3.up, outsideSpeed);
        colliders = Physics.OverlapSphere(transform.position, radius);
        foreach (Collider c in colliders)
        {
            if (c.GetComponent<rigidbody>() == null)
            {
                continue;
            }
            Rigidbody rigidbody = c.GetComponent<rigidbody>();
            Ray ray = new Ray(transform.position, c.transform.position - transform.position);
            RaycastHit hit;
            Physics.Raycast(ray, out hit);
            if (hit.distance &gt; maxPullInLength)
            {
                continue;
            }
            if (c.transform.position.z &gt; 8.5)
            {
                Vector3 Force = new Vector3(transform.position.x - c.transform.position.x, rigidbody.velocity.y / 2, transform.position.z - c.transform.position.z) * power;
                rigidbody.AddForceAtPosition(Force, transform.position);
            }
            rigidbody.AddForceAtPosition((transform.position - c.transform.position) * power, transform.position);
        }
    }
}

--------------
結果圖:

2018年4月14日 星期六

struct List 範例


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public struct data_data
{
    public data_data(string name, string nickname)
    {
        this.Name = name;
        this.NickName = nickname;
    }

    public string Name { get; private set; }
    public string NickName { get; private set; }
}

public class struct_example : MonoBehaviour {

    List list = new List();

 // Use this for initialization
 void Start () {

        list.Add(new data_data("小名", "名仔"));
        list.Add(new data_data("蠟筆小新", "小新"));

        //--------- print
        for (int x = 0; x < list.Count; x++)
            Debug.Log(list[x].Name +"," + list[x].NickName);
    }
}

2018年4月11日 星期三

斷詞系統之長詞優先法與詞位標籤_測試版

斷詞系統長詞優先法分為: 正向及反向,會產生岐異與未知詞上的問題,若是詞庫夠大就能解決了。 這裡只範例長詞優先法之程式。

已解決了正反向優先詞重覆字問題  2018/4/09 15:00
已添加詞位標籤  2018/4/09 15:00

語料庫下載_Mysql

------------SQL------------

using System.Collections.Generic;
using System.Data;
using System;
using MySql.Data.MySqlClient;
using System.Text;

namespace SQL
{
    public class SQL
    {
        public static MySqlConnection mySqlConnection;

        // DataBase Ip;
        private static string HOST = "SQL IP";
        public static string HOST_TYPE
        {
            set { HOST = value; }
            get { return HOST; }
        }

        // DataBase user Id
        private static string ID = "SQL USER ID";
        public static string ID_TYPE
        {
            set { ID = value; }
            get { return ID; }
        }

        // DataBase password
        private static string PASSWORD = "SQL PASSWORD";
        public static string PASSWORD_TYPE
        {
            set { PASSWORD = value; }
            get { return PASSWORD; }
        }

        // DataBase Name
        private static string DATABASE = "DATABASE_NAME";
        public static string DATABASE_TYPE
        {
            set { DATABASE = value; }
            get { return DATABASE; }
        }

        private static string PORT = "SQL PORT";
        public static string PORT_TYPE
        {
            set { PORT = value; }
            get { return PORT; }
        }

        // 連線結果
        public static string RESULT = "";

        // 訊息
        public static List string  MESSAGE = new List string ();

        // Connect to SQL;
        public static void openSqlConnection(string connction)
        {
            try
            {
                mySqlConnection = new MySqlConnection(connction);
                mySqlConnection.Open();
                RESULT = mySqlConnection.ServerVersion;
            }
            catch
            {
                RESULT = "無法連接資料庫";
            }
        }

        // Close SQL
        public static void closeSqlConnection()
        {
            mySqlConnection.Close();
            mySqlConnection.Dispose();
            mySqlConnection = null;
        }

        // SQL Query
        public static void DOQUERY(string sqlQuery)
        {
            IDbCommand dbcommand = mySqlConnection.CreateCommand();
            dbcommand.CommandText = sqlQuery;
            IDataReader reader = dbcommand.ExecuteReader();
            reader.Close();
            reader = null;
            dbcommand.Dispose();
            dbcommand = null;
        }

        #region Get DataSet
        public static DataSet GetDataSet(string sqlString)
        {
            DataSet ds = new DataSet();

            try
            {
                MySqlDataAdapter da = new MySqlDataAdapter(sqlString, mySqlConnection);
            }
            catch (Exception e)
            {
                throw new Exception("SQL:" + sqlString + "\n");
            }
            return ds;
        }
        #endregion

        // string to utf8
        public static string STRING_UTF8(string messae)
        {
            UTF8Encoding encoder = new UTF8Encoding();
            byte[] bytes = Encoding.UTF8.GetBytes(messae);
            string utf8ReturnString = encoder.GetString(bytes);

            return utf8ReturnString;
        }

        // 詞位標籤
        public static string INQUIRE_Lexical(string dataBaseTitle, string message)
        {
            string sqlText = "select * from " + dataBaseTitle + " where Message='" + message + "'";
            string str1 = "";

            MySqlCommand cmd = new MySqlCommand(sqlText, mySqlConnection);
            MySqlDataReader data = cmd.ExecuteReader();

            while (data.Read())
            {
                try
                {
                    str1 = data[5].ToString();
                }
                finally
                {

                }
            }

            data.Close();

            return str1;
        }


        // 資料庫查詢_Message(詞)
        // ※ 斷詞用_撈出可能性
        public static void INQUIRE_TABLE(string dataBaseTitle, string message)
        {
            string sqlText = "select * from " + dataBaseTitle + " where Message='" + message + "'";

            MySqlCommand cmd = new MySqlCommand(sqlText, mySqlConnection);
            MySqlDataReader data = cmd.ExecuteReader();

            while (data.Read())
            {
                try
                {
                    MESSAGE.Add(data[0].ToString());
                }
                finally
                {

                }
            }

            data.Close();
        }

        // 清除
        public static void MYSQL_MESSAGE_CLERA()
        {
            MESSAGE.Clear();
        }
    }
}


------------斷字處理功能------------

using System.Collections.Generic;
using UnityEngine;
using System.Collections;
using System.Text.RegularExpressions;

public class SegmentationSymbol
{
    // 斷詞標記括號
    private string[] specialSymbol = new string[] { "(", ")" };

    // 斷字狀態
    private string statusBroken;

    // 刪除符號字元 狀態: 1
    public string delectSymbol(string userMessage)
    {
        string strs = userMessage;

        for (int x = 0; x &lt; specialSymbol.Length; x++)
            strs = strs.Replace(specialSymbol[x], " ");

        return strs;
    }

    // 斷字字數
    private void status_conter(int status)
    {
        statusBroken = "";

        for (int x = 0; x &lt;= status; x++)
            statusBroken += @"\S";
    }

  
    // 斷字狀態
    public List<match> brokenSatus(string message, int status)
    {
        status_conter(status);

        List<match> match = new List<match>();
        MatchCollection splitResult = Regex.Matches(message, statusBroken, RegexOptions.IgnoreCase);

        foreach (Match test in splitResult)
            match.Add(test);

        return match;
    }

    // 刪除訊息
    public string delectWord(string message, int status)
    {
        string str = message;

        return str.Remove(status).ToString();
    }

   
    //  組合處理
    public List<string> delect_Word_Combination(string message, int status)
    {
        status_conter(status);

        string str = message;
        List<string> match = new List<string>();
        List<string> stringList = new List<string>();

        MatchCollection splitResult = Regex.Matches(str, statusBroken, RegexOptions.IgnoreCase);
        foreach (Match test in splitResult)
            match.Add(test.ToString());
        foreach (string strs in match)
        {
            stringList.Add(str.Replace(strs, ""));

            return stringList;
        }

        return stringList;
    }

    
    //  處理斷一次訊息
    public List<string> delect_oneWord(string message, int status)
    {
        status_conter(status);

        string str = message;
        List<string> match = new List<string>();
        List<string> stringList = new List<string>();

        MatchCollection splitResult = Regex.Matches(str, statusBroken, RegexOptions.IgnoreCase);
        foreach (Match test in splitResult)
            match.Add(test.ToString());
        foreach (string strs in match)
            stringList.Add(str.Replace(strs, ""));

        return stringList;
    }
}


------------斷詞程式------------

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text.RegularExpressions;
using System;

public class LongWordsFirst : MonoBehaviour
{

    public string str = "近年來知名夜市", logeWordForward, logeWordReverse, combination_string;

    private SegmentationSymbol segmentationSymbol = new SegmentationSymbol();
    private List<string> listMessage = new List<string>();
    private int messageNumber, messageNumber2, forward_Num;

    // 正向長詞優先法
    private List<string> longeWordForward_Message = new List<string>();

    // 正向長詞優先校正
    private List<string> forward_exclufr = new List<string>();

    // 反向長詞優先法
    private List<string> longeWordReverse_Message = new List<string>();

    // 正向詞位標籤
    private List<string> forwardLexical = new List<string>();
    // 反向詞位標籤
    private List<string> reverseLexical = new List<string>();

    // 長詞優先與詞位標籤完成
    public string fulfilForward, fulfilReverse, fulfil_ForwardLexical, fulfil_ReverseLexical;

    // 斷字系統資料表,文法組合資料表
    public static string dataBasetitle = "glossary", dataBasetitle2 = "grammar";

    void Start()
    {
        openDataBase();
    }

    // 打開資料庫
    void openDataBase()
    {
        string connectionString = string.Format("Server = {0}; Database = {1}; UserID = {2}; Password = {3}; Port = {4};", CMySql.HOST_TYPE, CMySql.DATABASE_TYPE, CMySql.ID_TYPE, CMySql.PASSWORD_TYPE, CMySql.PORT_TYPE);
        SQL.SQL.openSqlConnection(connectionString);
    }

    void OnGUI()
    {
        if (GUILayout.Button("測試"))
        {
            cutting_();
        }

        if (GUILayout.Button("詞位"))
        {
            // 導正順序
            StartCoroutine(order());
        }
    }

    void OnApplicationQuit()
    {
        SQL.SQL.closeSqlConnection();
    }

    // 切字
    private void cutting_()
    {
        listClear();

        // 正向優先輸入訊息
        logeWordForward = str;
        logeWordReverse = str;

        combination_string = str;

        messageNumber = logeWordReverse.Length;
        messageNumber2 = logeWordForward.Length;
        forward_Num = combination_string.Length;

        StartCoroutine(loneWordForward(logeWordForward.Length));
        StartCoroutine(longWordReverse(0));

        // 長詞詞位標籤
        StartCoroutine(forwardLable());
        StartCoroutine(reverseLable());

        // 長詞優先法校正
        StartCoroutine(ForwardAnalysis(0));
    }

    IEnumerator order()
    {
        while (true)
        {
            if (combination_string.Length == 0)
            {
                for (int x = forward_exclufr.Count - 1; x &gt;= 0; x--)
                    fulfilForward += forward_exclufr[x] + "|";

                for (int x = longeWordReverse_Message.Count - 1; x &gt;= 0; x--)
                    fulfilReverse += longeWordReverse_Message[x] + "|";

                for (int x = forwardLexical.Count - 1; x &gt;= 0; x--)
                    fulfil_ForwardLexical += forwardLexical[x] + "|";

                for (int x = reverseLexical.Count - 1; x &gt;= 0; x--)
                    fulfil_ReverseLexical += reverseLexical[x] + "|";

                break;
            }

            yield return new WaitForSeconds(0.5f);
        }
    }

    // 反向長詞詞位標籤
    IEnumerator reverseLable()
    {
        int x = 0;

        while (true)
        {
            try
            {
                if (x &lt; longeWordReverse_Message.Count)
                {
                    reverseLexical.Add(SQL.SQL.INQUIRE_Lexical(dataBasetitle, longeWordReverse_Message[x]));
                    x++;
                }
            }
            catch
            {
                break;
            }

            yield return new WaitForSeconds(0.5f);
        }
    }

    // 正向長詞詞位標籤
    IEnumerator forwardLable()
    {
        int x = 0;
        while (true)
        {
            try
            {

                if (x &lt; forward_exclufr.Count)
                {
                    forwardLexical.Add(SQL.SQL.INQUIRE_Lexical(dataBasetitle, forward_exclufr[x]));
                    x++;
                }

            }
            catch
            {
                break;
            }
            yield return new WaitForSeconds(0.5f);
        }
    }

    // 正向長詞優先法
    IEnumerator loneWordForward(int lenght)
    {
        while (true)
        {
            foreach (Match match1 in segmentationSymbol.brokenSatus(logeWordForward, logeWordForward.Length))
            {
                SQL.SQL.INQUIRE_TABLE(dataBasetitle, match1.ToString());

                foreach (string sqlMessage in SQL.SQL.MESSAGE)
                {
                    if (sqlMessage == match1.ToString())
                    {
                        longeWordForward_Message.Add(match1.ToString());

                        logeWordForward = segmentationSymbol.delectWord(logeWordForward, messageNumber2);
                    }

                }

                SQL.SQL.MYSQL_MESSAGE_CLERA();
            }



            foreach (Match match in segmentationSymbol.brokenSatus(logeWordForward, messageNumber2))
            {
                SQL.SQL.INQUIRE_TABLE(dataBasetitle, match.ToString());
                foreach (string str in SQL.SQL.MESSAGE)
                {
                    if (str == match.ToString())
                        longeWordForward_Message.Add(str);
                    logeWordForward = inspection(logeWordForward, longeWordForward_Message);
                    messageNumber2 = logeWordForward.Length;

                }

                SQL.SQL.MYSQL_MESSAGE_CLERA();
            }

            if (messageNumber2 &gt;= 0)
            {
                messageNumber2 -= 1;
            }

            yield return new WaitForSeconds(0.5f);
        }
    }

    // 後向長詞優先法
    IEnumerator longWordReverse(int lenght)
    {
        while (true)
        {
            foreach (Match match in segmentationSymbol.brokenSatus(logeWordReverse, logeWordReverse.Length))
            {
                SQL.SQL.INQUIRE_TABLE(dataBasetitle, match.ToString());
                foreach (string str in SQL.SQL.MESSAGE)
                {
                    if (str == match.ToString())
                    {
                        longeWordReverse_Message.Add(match.ToString());
                        logeWordReverse = segmentationSymbol.delectWord(logeWordReverse, match.Length);
                    }
                }
            }

            SQL.SQL.INQUIRE_TABLE(dataBasetitle, logeWordReverse);

            foreach (string str in segmentationSymbol.delect_Word_Combination(logeWordReverse, lenght))
            {
                SQL.SQL.INQUIRE_TABLE(dataBasetitle, str);

                foreach (string sqlMessage in SQL.SQL.MESSAGE)
                {
                    if (sqlMessage == str)
                    {
                        longeWordReverse_Message.Add(sqlMessage);
                        logeWordReverse = segmentationSymbol.delectWord(logeWordReverse, logeWordReverse.Length - sqlMessage.Length);
                        lenght = 0;
                    }
                }
            }

            lenght += 1;

            foreach (string str22 in SQL.SQL.MESSAGE)
            {
                if (str22 == logeWordReverse)
                {
                    longeWordReverse_Message.Add(logeWordReverse);
                    logeWordReverse = segmentationSymbol.delectWord(logeWordReverse, logeWordReverse.Length - str22.Length);
                }
            }


            if (lenght &gt;= combination_string.Length)
                lenght = 0;

            yield return new WaitForSeconds(0.5f);
        }
    }

    // 正向長詞優先法校正
    IEnumerator ForwardAnalysis(int lenght)
    {
        while (true)
        {

            foreach (string str in segmentationSymbol.delect_Word_Combination(combination_string, lenght))
            {
                Debug.Log(str);
                for (int x = 0; x &lt; longeWordForward_Message.Count; x++)
                {
                    if (str == longeWordForward_Message[x])
                    {
                        forward_exclufr.Add(str);
                        combination_string = segmentationSymbol.delectWord(combination_string, combination_string.Length - longeWordForward_Message[x].Length);
                        longeWordForward_Message.Remove(str);
                        lenght = 0;
                    }
                }
            }
            lenght += 1;

            for (int x = 0; x &lt; longeWordForward_Message.Count; x++)
            {
                if (combination_string == longeWordForward_Message[x])
                {
                    forward_exclufr.Add(combination_string);
                    combination_string = inspection(combination_string, forward_exclufr);
                    longeWordForward_Message.Remove(str);
                    lenght = 0;
                }
            }

            if (lenght &gt;= combination_string.Length)
                lenght = 0;

            yield return new WaitForSeconds(0.5f);
        }
    }

    // 檢查沒有數據
    private string inspection(string message, List<string> list)
    {
        string str = message;

        foreach (string str1 in list)
        {
            str = str.Replace(str1, "");
        }

        return str;
    }

    // list 清除
    private void listClear()
    {
        longeWordForward_Message.Clear();
        longeWordReverse_Message.Clear();
        forward_exclufr.Clear();
    }
}



------------結果圖------------



2018年4月5日 星期四

指定路徑搜尋所有子資料

這是示範專案使用的是Unity UI 功能當成介面,文字顯示部分則是用InputField之物件來做顯示,主要是為了方便使用。

UI_Canvas 物件需要:
  • InputField - 命名: Path
  • Scrollbar - 命名: Scrollbar_FileName
  • Button - 命名: Enter

InputField 物件與組件:
  • 子物件(Text) - 命名: FileName ※屬性 Text: 清空。
  • InputField: 關閉功能。
  • Scroll Rect: Content(放入Text子物件),Horizontal 勾勾拿掉,Vertical Scrolbar (放入Scrollbar 物件)。
  • Mask。

Scrollbar 物件與組件: 
  • scrolbar: Direction(更改)


Button  物件與組件:

  • 子物件(Text)-命名: btnMessage ※屬性Text: 輸入確定。
物件共同組件設定:

















程式碼(放到Canvas 物件) 設定:
















------------------------------------

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;
using System;
using UnityEngine.UI;

public class Article : MonoBehaviour
{
    public GameObject pathBack, scrollbar_FilePatch, path_Message, enter;

    // 檔案位置
    private string patch = @"C:\Users\JohnLin\Desktop\測試\";
    public string path_Type
    {
        set { patch = value; }
        get { return patch; }
    }

    // 檔案位置List
    private List<string> file_patch = new List<string>();

    private string patch_result;

    public float pointX, pointY;

    // 讀取文字檔內容
    private string readtxtMessage;

    // 刪除重復編號
    private int delectNumber;

    void Start()
    {
        // 按鈕屬性
        button_(enter, 0.12f, 0.58f, 0.2f, 30);
    }
   
    void Update()
    {
        // 顯示路徑背景
        image_(pathBack, 0.42f, 1.32f, 0.8f, 1.2f);

        // 拉霸
        scrollbar_(scrollbar_FilePatch, 0.86f, 1.4f, 0, 0);
    }

    // Button 屬性
    Button button_(GameObject obj, float width, float height, float sizeX, float sizeY)
    {
        Button btn = obj.GetComponent<Button>();

        // posistion
        btn.transform.position = new Vector2(Screen.width / 2 * width, Screen.height / 2 * height);
        // imageSize
        btn.image.rectTransform.sizeDelta = new Vector2(Screen.width / 2 * sizeX, sizeY);

        switch (btn.name)
        {
            case "Enter":
                btn.onClick.AddListener(() => btnOnClick_Enter());
                break;
        }

        return btn;
    }

    // 探聽(確定)
    public void btnOnClick_Enter()
    {
        clearList();
        StartCoroutine(readFire());
        patch_result = "";

        for (int x = 0; x < file_patch.Count; x++)
            patch_result += file_patch[x] + "\n";

        text_(path_Message).text = patch_result;
    }

    // Image 屬性
    Image image_(GameObject obj, float width, float height, float sizeX, float sizeY)
    {
        Image image = obj.GetComponent<Image>();

        // posistion
        image.rectTransform.position = new Vector2(Screen.width / 2 * width, Screen.height / 2 * height);

        // imageSize
        image.rectTransform.sizeDelta = new Vector2(Screen.width / 2 * sizeX, Screen.height / 2 * sizeY);

        return image;
    }

    // 拉霸
    Scrollbar scrollbar_(GameObject obj, float width, float height, float sizeX, float sizeY)
    {
        Scrollbar scrollbar = obj.GetComponent<Scrollbar>();
        scrollbar.transform.position = new Vector2(Screen.width / 2 * width, Screen.height / 2 * height);
        //scrollbar.size = 12;

        return scrollbar;
    }

    // Text 屬性
    Text text_(GameObject obj)
    {
        Text text = obj.GetComponent<Text>();
        text.horizontalOverflow = HorizontalWrapMode.Wrap;
        text.verticalOverflow = VerticalWrapMode.Overflow;

        return text;
    }

    // 自動閱讀檔案
    IEnumerator readFire()
    {
        DirectoryInfo di = new DirectoryInfo(path_Type);

        foreach (FileInfo fileInfo in di.GetFiles("*.*", SearchOption.AllDirectories))
        {
            file_patch.Add(fileInfo.ToString());
        }
     
        yield return new WaitForSeconds(0.5f);
    }

    /// <summary>
    /// 讀取文建資料
    /// </summary>
    /// <returns></returns>
    private List<string> readFileTxtMessage(string str)
    {
        StreamReader streamReader = new StreamReader(str);

        List<string> readTxtMessageList = new List<string>();
        readTxtMessageList.Clear();

        while ((readtxtMessage = streamReader.ReadLine()) != null)
            readTxtMessageList.Add(readtxtMessage);

        streamReader.Close();
        return readTxtMessageList;
    }

    // 清除List
    void clearList()
    {
        file_patch.Clear();
    }
}

----------------------

結果圖: