赞
踩
在C#下运行Python可能有不同的原因。其中一些原因包括:
为实现Python和C#之间的互操作性,有两个库可供选择:IronPython和pythonnet:
根据具体的用例和要求,选择适合的库将提供更好的灵活性和互操作性。
下面使用 c#和IronPython 写一段获取天气的热门旅游城市的代码,首先是c#代码部分:
using IronPython.Hosting; using IronPython.Runtime; using Microsoft.Scripting.Hosting; using System; using System.Collections.Generic; using System.IO; using System.Xml; namespace WeatherInfo { class Program { static void Main(string[] args) { // 亿牛云 爬虫代理加强版 // 设置爬虫代理IP的主机、端口、用户名和密码 string proxyHost = "www.16yun.cn"; int proxyPort = 31000; string proxyUsername = "16YUN"; string proxyPassword = "16IP"; // 创建Python脚本引擎 var engine = Python.CreateEngine(); var scope = engine.CreateScope(); // 设置代理IP engine.GetSysModule().SetVariable("proxy_host", proxyHost); engine.GetSysModule().SetVariable("proxy_port", proxyPort); engine.GetSysModule().SetVariable("proxy_username", proxyUsername); engine.GetSysModule().SetVariable("proxy_password", proxyPassword); // 加载并执行Python脚本 engine.ExecuteFile("get_weather.py", scope); // 获取结果 var cities = (List<string>)scope.GetVariable("cities"); var temperatures = (List<string>)scope.GetVariable("temperatures"); var times = (List<string>)scope.GetVariable("times"); // 创建XML文档 XmlDocument xmlDoc = new XmlDocument(); XmlElement root = xmlDoc.CreateElement("WeatherData"); xmlDoc.AppendChild(root); for (int i = 0; i < cities.Count; i++) { XmlElement cityElement = xmlDoc.CreateElement("City"); cityElement.SetAttribute("Name", cities[i]); XmlElement temperatureElement = xmlDoc.CreateElement("Temperature"); temperatureElement.InnerText = temperatures[i]; XmlElement timeElement = xmlDoc.CreateElement("Time"); timeElement.InnerText = times[i]; cityElement.AppendChild(temperatureElement); cityElement.AppendChild(timeElement); root.AppendChild(cityElement); } // 保存XML文件 xmlDoc.Save("weather_data.xml"); Console.WriteLine("Weather information saved to weather_data.xml."); } } }
请将上述代码保存为 Program.cs 文件,并创建一个名为 get_weather.py 的Python脚本文件,脚本内容如下:
import requests from bs4 import BeautifulSoup # 亿牛云 爬虫代理加强版 代理IP设置 proxy = { 'http': 'http://%(proxy_username)s:%(proxy_password)s@%(proxy_host)s:%(proxy_port)s/' % { 'proxy_username': proxy_username, 'proxy_password': proxy_password, 'proxy_host': proxy_host, 'proxy_port': proxy_port }, 'https': 'http://%(proxy_username)s:%(proxy_password)s@%(proxy_host)s:%(proxy_port)s/' % { 'proxy_username': proxy_username, 'proxy_password': proxy_password, 'proxy_host': proxy_host, 'proxy_port': proxy_port } } # 使用百度搜索获取天气信息 def get_weather_info(city): search_url = 'https://www.baidu.com/s' params = { 'wd': city + '天气', 'rsv_spt': '1', 'rsv_iqid': '0xc2442a04000970
上面的代码是使用C#和IronPython编写的一个简单的程序,旨在通过百度搜索获取中国旅游城市的天气信息,并将地区、温度信息和时间进行统计,最后将结果存储到XML文件中。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。