0

I have a wordcloud in python, i want to use MVC to call the python .py and show the output on my View. Now I can already call the python .py in c#, it can successfully run and show the wordcloud. But i dont know how to display the wordcloud output on my View.
I have referenced this pageHow do I execute and return the results of a python script in c#?.

Here is my wordcloud.py

# -*- coding: utf-8 -*-
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt
import pyodbc, time
import pandas as pd
import numpy as np
import sys
import jieba
import jieba.posseg as pseg
from io import BytesIO
import base64
from datetime import  datetime, timedelta
from collections import Counter
from PIL import Image


def wc():
    #temp=sys.argv[1]
    #print("ssssssssssssssssssssssssssssssssssss")
    server = 'LAPTOP-22AVH2GL\MSSQLSERVER01'
    #server = 'WILLY\SQLEXPRESS'
    database = 'Project2'
    uid = 'sa'
    pwd = 'neil0627'
    #pwd = 'h24664034'
    cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+uid+';PWD='+pwd)
    cursor = cnxn.cursor()
    #sqlcom = "SELECT DISTINCT JIEBA, COUNT(JIEBA) FROM Jieba WITH(NOLOCK) GROUP BY jieba" #News.api #Project
    sqlcom = "SELECT DISTINCT JIEBA, COUNT(JIEBA) FROM Jieba1 WITH(NOLOCK) GROUP BY jieba" #News.api #Project2
    news = pd.read_sql(sqlcom, con=cnxn) 
    print(news)
    df3 = np.array(news)
    print(df3)
    df4 = dict(df3.tolist())
    print(df4)
    
    font_path = r'D:\anaconda3\Lib\site-packages\wordcloud\SimHei.ttf'
    #mask = np.array(Image.open("D:/456.png"))
    # back_color = imageio.imread("./taiwan.png")
    #myWordClode = WordCloud(width=850, height=850, background_color="white", 
    #                          font_path=font_path, colormap="Dark2",mask=mask)
    myWordClode = WordCloud(width=850, height=850, background_color="white", 
                               font_path=font_path, colormap="Dark2")
    myWordClode.generate_from_frequencies(df4)
    # use PIL show the wordcloud
    fig = plt.figure()
    #fig = plt.figure(figsize=(20,10))
    plt.imshow(myWordClode)
    plt.axis("off")
    #fig.savefig("testtttttt.png")
    plt.show()
    #sio = BytesIO()
    #plt.savefig(sio, format='png')
    #data = base64.encodebytes(sio.getvalue()).decode()
    #print(data)
    
    myWordClode.to_file('wcp1.png')
wc()









And here is my controller

private string run_cmd(string cmd, string args)
        {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = @"C:/Users/user/AppData/Local/Programs/Python/Python38-32/python.exe";
            start.CreateNoWindow = true;
            start.Arguments = string.Format("{0} {1}", cmd, args);
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    string result = reader.ReadToEnd();
                    //Console.Write(result);
                    //string stderr = process.StandardError.ReadToEnd();
                    //string stdout = process.StandardOutput.ReadToEnd();
                    //Debug.WriteLine("STDERR: " + stderr);
                    //Debug.WriteLine("STDOUT: " + stdout);
                    return result;
                }

            }
        }

I try to use Viewbag to pass the image to View.I dont know if this is right.Here is my code.

ViewBag.wordcloud = run_cmd("D:/Python/wordcloudjieba.py", "Some Input");

Has anyone to do this before? Thanks for any idea!!

li neil
  • 11
  • 2
  • The output of wordclound is png image. The python same script I've seen is taking the byte array from word-cloud and displaying in a view. So normally you would use Image.FromStream. – jdweng Oct 07 '20 at 16:18
  • What is the type of the wordcloud? An image? if so you will need to get it's binary contents, and make it available via an ` – Jonathan Oct 07 '20 at 16:18
  • @jdweng OK! I will go search Image.FromStream – li neil Oct 07 '20 at 16:31
  • @Jonathan YES, is png. So i need to change `.py` output from png to binary contents in python,right? – li neil Oct 07 '20 at 16:37

0 Answers0