iT邦幫忙

1

以C#為主,利用python計算數值問題

嗨 各位大大 我將程式碼改成這樣,有計算出結果了,可是會一直顯示出0,請問為甚麼會這樣?!

c#
class Program
    {
        static void Main(string[] args)
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Enabled = true;
            timer.Interval = 3000;
            timer.Start();
            timer.Elapsed += new System.Timers.ElapsedEventHandler(test);

            Console.ReadKey();
        }
        private static void test(object source, ElapsedEventArgs e)
        {
           
            string line;

            System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\wkj88\Desktop\teraterm.txt");
            while ((line = file.ReadToEnd()) != null)
            {
                
                ScriptRuntime pyRunTime = Python.CreateRuntime();
                dynamic obj = pyRunTime.UseFile(@"C:\Users\wkj88\hello.py");
                Console.Write(obj.welcome(line));
           

            }
            file.Close();
            Console.ReadKey();
        }
    }
python

def welcome(rms):
    a = rms.replace('\r\n','')
    results = list(map(int, a))

    return sum(results)

https://ithelp.ithome.com.tw/upload/images/20181108/20110704TKdWRZeYEd.png

看更多先前的討論...收起先前的討論...
froce iT邦大師 1 級 ‧ 2018-11-07 12:18:56 檢舉
這是透過 ironpython 去溝通的,所以你必須要裝。
http://ironpython.net/
https://blog.csdn.net/taonull/article/details/42923015

不過ironpython據我所知,python3 方面目前沒啥開發者,所以只能用python2開發。
froce iT邦大師 1 級 ‧ 2018-11-07 12:24:57 檢舉
或者你可以考慮用API模式去溝通。

不過你用的方式很奇怪,python的運算速度絕對不會比C#快,每三秒讀檔這種事也不一定要用C#。
我猜你python裡面應該是要接機器學習等運算?如果是的話建議直接用python讀檔,或許更省事。
謝謝您的回覆!! 我有裝ironpython了,會使用python是因為在演算法的編寫上比較容易,而我遇到的問題是,如果我每次只傳送一個值,並將在python 那邊的運算改成return rms+1的話,他是可以回傳+1後的數值,但是我想要一次傳一個陣列過去時,就沒有回傳值回來了。
謝謝 force大大的回應,我後來將程式碼改這樣了,請問是哪裡出了問題呢?
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
JamesDoge
iT邦高手 1 級 ‧ 2023-01-30 08:17:51

看起來問題出在 Python 腳本中的數據處理方式上。

函數 "welcome" 使用 "replace" 方法將所有字符串 "\r\n" 替換為空字符串,但這不是將字符串分割為單獨值的正確方法。

要將字符串分割為單獨值,您可以使用 "split" 方法。

def welcome(rms):
    results = list(map(int, rms.split('\r\n')))

    return sum(results)

我要發表回答

立即登入回答