要怎么能力学会Python编程呢?我感觉最好的办法就是“做中学,玩中学”,只有亲自动手去做Python我的项目,能力学以致用,真正把握这门编程语言,为我所用。编程玩家俱乐部推出了挑战100+ Python我的项目,代码和文档开源在:https://github.com/zhiwehu/10... 来吧,让咱们动手做起来!
中英文翻译
我的项目需要
- 在命令行窗口运行
- 当程序运行时,会要求咱们输出中文或者英文单词或者句子,而后程序会主动翻译成对应的英语或者中文
- 当输出q字母,程序不再询问并完结
Python编程知识点
- while循环
- 用户输出字符串
- 条件判断
- 字典数据
- http post申请
- requests 模块 (须要应用
pip install requests
装置)
参考代码
import requestsurl = 'https://fanyi.baidu.com/sug'while True: text = input('请输出中文或者英语:').strip() if text == 'q': break data = {'kw': text} resp = requests.post(url, data) found = False if resp.status_code == 200: data = resp.json() if data['errno'] == 0: ds = data['data'] for kv in ds: if kv['k'] == text: found = True print(kv['v']) if not found: print('没有找到') else: print(data) else: print(resp.content)
运行测试
将代码保留为2.py,而后在控制台运行:
python 2.py