挑战100+Python项目2:中英文翻译

1,275 阅读1分钟

要怎么才能学会Python编程呢?我觉得最好的方法就是“做中学,玩中学”,只有亲自动手去做Python项目,才能学以致用,真正掌握这门编程语言,为我所用。编程玩家俱乐部推出了挑战100+ Python项目,代码和文档开源在:github.com/zhiwehu/100… 来吧,让我们动手做起来!

中英文翻译

项目需求

  1. 在命令行窗口运行
  2. 当程序运行时,会要求我们输入中文或者英文单词或者句子,然后程序会自动翻译成对应的英语或者中文
  3. 当输入q字母,程序不再询问并结束

Python编程知识点

  • while循环
  • 用户输入字符串
  • 条件判断
  • 字典数据
  • http post请求
  • requests 模块 (需要使用pip install requests安装)

参考代码

import requests

url = '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

image.png