python单词怎么写_python 写的查单词的脚本

最近在学习Python,看Document时,好多不认识的单词,每次打开网页有道查询嫌麻烦,自己手写了一个mini的脚本,显示网页的单词解释,功能有限,希望大家给点指点。用到了BeautifulSoup模块。

以单词'hello'为例, 网页代码是这样的:

  • int. 喂;哈罗
  • n. 表示问候, 惊奇或唤起注意时的用语

[

复数

hellos或helloes

过去式

helloed

过去分词

helloed

现在分词

helloing

]

这个是词组解释的html代码:

短语

Hello Kitty

凯蒂猫

;

昵称

;

凯帝猫

;

匿称

Hello Fred

你好

Hello Android

创建

;

创立

hello barbie

哈啰芭比

Hello English

学英语

;

新纪元小学英语

;

欢唱律动学英语

;

律动欢唱学英

Hello Andrid

创建

;

创立

Hello Schoolgirl

纯情漫画

;

纯真漫画

;

韩国唯美爱情故事

Hello Yellow

浅草黄

Hello Booky

布奇乐乐园

  更多 收起网络短语
    Python脚本程序:

# coding:utf-8

# Copyright 2013--2015.

# Licensed under the Apache License, Version 1

# http://www.apache.org/licenses/LICENSE-2.0

# Word_Searching Script

# Author: fish

# Email: fsh267@gmail.com

# http://www.love67.net/?p=608 # usage1: 'python **.py word' to find the word's explination or

# usage2: 'python **.py word -detail' to list the phrase of the word

from bs4 import BeautifulSoup

import sys

import urllib2

def input_error():

print "usage1: 'python **.py word' or "

print "usage2: 'python **.py word -detail"

def main():

length = len(sys.argv)

# 读入命令行

if length < 2:

input_error()

sys.exit()

else:

word = sys.argv[1]

# url是有道翻译的对应网页

url = 'http://dict.youdao.com/search?le=en&q=%s&keyfrom=dict.index' %word

# urlopen函数调用

#print url

data = urllib2.urlopen(url).read()

#print data

# 将data网页源代码放到soup中,便于匹配

soup = BeautifulSoup(data)

# soup.find() 可以放入标签和class名称

word_div = soup.find('div', 'trans-container')

if not word_div:

print 'word does not exists'

sys.exit()

# word_div存了一个标签,每个单词意思,存在每个

**中,格式化输出,不带''

for word_explination in word_div.find_all('li'):

print str(word_explination)[4: -5]

#第二种输入,还得显示出单词组成的短语

#BeautifulSoup提供的find函数可以查找'p', 'a','span'等html标志语言模块

if length == 3:

if sys.argv[2] != '-detail':

input_error()

else:

raw_explination = ''

span = soup.find_all('p', 'wordGroup')

#最后一组词组有问题,删去了

for element in span[ : -1]:

link = element.find('a')

#转化成字符串,用于定位到解释那里

raw_explination += str(element)

location = raw_explination.find('')

#格式化单词解释,长度为7,

长度为4, 只采用第一个意思

explination = raw_explination[location + 7 : -4].split()[0]

#python 自带的输出对齐, ljust(num), rjust(num)

print link.string.ljust(25), explination

raw_explination = ''

if __name__ == '__main__':

main() 再次感谢!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值