本帖最后由 xiaoxue 于 2019-3-4 20:51 编辑 3 q/ L0 `0 F' \# ], L
- . T) }' j$ Q7 `' w/ S* J! x
- # -*- coding: UTF-8 -*-
" _- {4 [; C) Q) B- L! }' j- ` - import requests
7 n: W2 e9 t; t+ y% B6 B9 i - import os3 J+ P8 o( }" m; A
- import subprocess
' a) M1 l; J5 \) y$ B8 `3 w - import sys+ \* l: X) q0 {3 g" I
- from tqdm import tqdm; |: a( p. i2 b' `7 n6 i3 I" r6 j* e
- import time,random
" V$ s! s9 s+ F F5 o - from HTMLParser import HTMLParser
9 ~& u* c1 t+ r - import sys
: |+ R5 d6 T$ `$ ` - reload(sys) 7 P0 K" T9 ~' R
- sys.setdefaultencoding('utf8') , S% f0 i$ B8 H2 q5 ?6 ]7 v
. c4 F( n8 S4 B8 Z; X- class WebRequest(object):
( U3 N. J. y0 u. N0 y3 b% H) ^8 y7 Q - def __init__(self, *args, **kwargs):
: w' @) r9 c7 u7 g0 I& X$ v2 K - pass
1 _# ], x* C) ^! i$ I: k& S) y, `
7 I" x# k3 } r9 r' O; t- j. K- @property
: i3 ^1 @! M' t' _* G: S2 { - def user_agent(self):: W {% x! t. o+ d
- """
7 E4 Y, ^# i$ r; y - return an User-Agent at random( S) X; w$ U7 E' N
- :return:
: A' R" p _1 s& h, z+ k) d( R9 ` - """
' P0 r7 \/ E5 \) |% l - ua_list = [& _4 x. h9 E; r8 ]- d' s. c( z
- 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101',; Z- z5 z! x. W5 [% c) g
- 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122',, x& j3 D4 T9 w0 u" ?, K8 Z
- 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71',
8 r' {$ H ?# k1 Y) E1 f - 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95',
: e. _+ d* Z% [ - 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71',
8 b! [6 e0 ~) Z# U9 T1 I - 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)',
# P6 r4 d& [- \* X - 'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50',
P" L$ _1 x3 I) a9 o8 I w$ L - 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0',; A0 K4 `8 |7 T/ C+ S% I" v
- ]' i; r; M p" x+ s' S+ Z
- return random.choice(ua_list)* C C" d2 _$ P2 n, t
- & ^2 d5 k1 T {& ]- D$ ~# A" q! S
- @property* m" Y! O& D" ^/ h4 G
- def header(self):
' R3 j7 a) J+ F' w J" _ - """
9 _5 s8 V, p4 N6 r; R9 m - basic header8 j5 v, w) v8 I1 \' X l% P
- :return:. X; R! X# B' h# ^) T0 \0 g* D5 @, R
- """
( W9 C" o. j | - return {'User-Agent': self.user_agent,9 |! Q% k6 E U$ y8 f
- 'Accept': '*/*',+ ?" U8 I, D0 }4 r" W- a
- 'Connection': 'keep-alive',! e; R5 W5 i t1 Y' n
- 'Accept-Language': 'zh-CN,zh;q=0.8'}
# T/ v, g4 s% o3 k5 F( G! \ - % O! T2 l0 T# N
- def get(self, url, header=None, retry_time=5, timeout=30,& G8 W h/ z* v. [) t8 Q8 t
- retry_flag=list(), retry_interval=5, *args, **kwargs):
8 c( r/ b1 s% I% ^0 j: I' t - """" I e6 C4 d7 m5 P4 l$ d
- get method
* G9 H& J) v) n1 R; R7 i - :param url: target url3 i- c8 V, h, l" @" [$ B
- :param header: headers5 }8 V- A: k7 `
- :param retry_time: retry time when network error
' w) F. ?# m' }" \% o - :param timeout: network timeout
; N2 F* A$ u. R3 E1 g - :param retry_flag: if retry_flag in content. do retry
, P5 R. l8 i2 Y* n - :param retry_interval: retry interval(second)8 ]1 U- P4 }8 V
- :param args:# b- R# E" n9 Q! |
- :param kwargs:
0 S/ r/ p8 F) Y' f/ D6 T# p - :return:
$ z; G. ^% ^$ t% d! s: ] - """
' Y% A& J- u0 V( P - headers = self.header( y1 C8 F: _7 U- v
- if header and isinstance(header, dict):
7 S: h6 H- ^- G1 Y - headers.update(header)
' k* O8 j% m% H! F - while True:
8 I* c1 L# O# @4 U - try: X# u, S& J! E$ \* }% d
- html = requests.get(url, headers=headers, timeout=timeout, stream=True)3 n& F- N3 u+ ?6 [
- print 'content size: %d' % len(html.content)8 v2 Y+ d5 s+ B$ s0 |
- if any(f in html.content for f in retry_flag):- }& \3 R1 X5 `5 L3 t* t; Y. e
- raise Exception! C) ?, M6 ?. k6 k4 l% T3 j6 h
- if not html.content:
$ e6 U2 `* A; r0 f& M - print 'content is Null,retry...~' + url q) |' i& Y) M2 h3 \: i7 ]
- raise Exception. f3 z4 u, Q7 l: [+ a
- return html
+ \; I6 z6 p7 x4 o7 Y - except Exception as e:
) K+ k" \* v* [+ t1 q) p1 E( R - print(e)
1 d# {3 [0 ~+ m$ M- E. b4 E - 5 j& V' R- T& M. [+ C2 F& ^
- * G2 R' h# n9 A P/ R$ W
- def DownloadAudio(url, path, refer=None):% K7 f: |% a% q- \
- with open(path, 'wb') as handle:. x6 ]' f: r4 C" x# M6 }
- if refer:+ d4 [2 d5 J/ \. C, l8 w7 W
- hdr = {
- d4 M. K. s5 x - 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
. x* r0 H" ?: D v. U - 'Referer': refer}+ p5 P8 o' W+ q: m# u* Y+ ]" o/ `0 B
- else:, s" @3 L9 w k) s5 |, x
- hdr = {3 f/ z# Z( P9 ^: X3 m
- 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
% u2 W. T7 ?1 t/ d k$ R3 A - 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',; W) N. w$ p, j6 x0 h% c
- 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',% [1 i1 ~. q/ s% _( ^$ Q
- 'Accept-Encoding': 'none',8 Y: n- v" Z2 _1 {. [: t; s- J
- 'Accept-Language': 'en-US,en;q=0.8',- r! f1 E; a1 j; }* W& P3 P3 D
- 'Connection': 'keep-alive'}
! ]; z& g! E' H2 w - wr = WebRequest() ?7 z7 H8 f! ^( N5 J+ T
- #print hdr7 f7 v( z9 t; q+ r) b6 |: \
- response = wr.get(url,header=hdr)5 |' u0 n- L1 ~2 Q# `4 C' q
- #html = requests.get('https://www.example.com', proxies={"http": "http://{}".format(proxy)}); C; e0 \9 a0 R6 O& y' r: f" ?0 j
- #response = requests.get(url, stream=True, headers={'User-agent': 'Mozilla/5.0'})
s+ U- q! p9 L b - #print url3 A5 ]* @# Q& u! u- B6 d
- for block in tqdm(response.iter_content(),ascii=True, desc='ImageDownload'):( K$ N. A/ H& L" n1 c& s4 e8 o
- if not block:
4 N, C' ]3 U% j1 m - break" V% j: o. a0 o, s3 o# y1 q2 o9 O; ~5 U
- handle.write(block)
/ G% `$ a1 _/ _' z
1 _8 {' p* r* V" v, p/ q- def translate(to_translate, to_langage="auto", langage="auto"):* T7 I, f% ?' W8 S. ?5 L" s
- '''Return the translation using google translate
7 [& E' H" J3 ^6 S, k. C$ ^) k - you must shortcut the langage you define (French = fr, English = en, Spanish = es, etc...), _2 X+ i) N1 b3 N' N; B% S
- if you don't define anything it will detect it or use english by default
( f: t6 v& @; u: w9 t) u - Example:) @% }5 v. G5 q4 X- W& @0 s! A
- print(translate("salut tu vas bien?", "en"))
% U/ X/ }) D [0 f; [4 D/ l. I - hello you alright?'''2 O0 z9 Y& e! J$ F
- agents = {'User-Agent':"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)"}" I, A9 {+ {0 G
- before_trans = 'class="t0">'+ q/ G7 z3 D9 C5 _' R1 S+ N# M
- link = "http://translate.google.com/m?ie=UTF-8&hl=%s&sl=%s&q=%s" % (to_langage, langage, to_translate.replace(" ", "+"))% ], ^6 O- Q+ j& L- l
- request = requests.get(link, headers=agents)
0 x* L2 L) U7 Y8 q7 e( l - page = request.content
j) S. e5 Z. V C0 O$ s - #print page0 f' }# X8 C0 m
- result = page[page.find(before_trans)+len(before_trans):]
. P9 G9 l; M7 ]. {3 c, B - result = result.split("<")[0]
7 }( |! U: o/ P+ @1 l - return result
, L. W# {6 T; b7 V/ d6 D* j, u# H - / z- B: ^) v3 U7 n8 L. c
- tsxt_sen = []3 d! k- h. }1 Y0 A) C T# Q' X
- from nltk.tokenize import sent_tokenize
4 t9 E9 E1 m1 Y' l0 I4 j# K - def sentence_split(sentence): # 编写分句函数
9 \% f8 X+ o0 X! \7 E3 z+ ^2 r/ B' c - text_sen = []5 o! Z0 c9 i; ^- N9 h. M
- for s in sentence.split(','):
2 b# I4 n# Q. t5 F. j, ] - # if '?' in s:
, i3 u; N7 a4 B* [1 Q& x - # tsxt_sen.extend(s.split('?'))
4 @3 L' c0 W4 Y$ C @3 F! I: b - # elif ',' in s: V7 `" n. {- g7 c# a8 \
- # tsxt_sen.extend(s.split(','))+ l* q0 Y, \- |
- # else:7 a& H. O) B& T1 S, K
- text_sen.append(s)
$ J8 O9 i$ f* s$ p* I - return tsxt_sen/ V3 O0 c( S. K6 ^
- & { R6 L$ Z* g# V+ [& a: r
- $ }# C3 \. b9 h$ u) J
- str = '''
3 Y/ Q4 Y; o; @; | - It has not quite been greeted with the enthusiasm of the bottles of Scotch in the novel Whisky Galore, but the arrival of a cargo of pineapples on the shores of northern Scotland has sent scavengers rushing to the beach.3 [7 U6 t) P$ M" m9 t
0 J* B0 ]9 v4 [( o+ a8 ^- The fruit, which has appeared on Shetland and on beaches across the Western Isles, is thought to have come from several containers lost overboard in the Atlantic last October by cargo ship MV Lombok Strait.
4 `+ J# s- u0 m9 [" o - . x" { w% B1 n, K% W9 u& l: D/ x+ r0 L
- Shetland islanders have now shared photos of their fruitful haul, in a story that echoes the plot of Whisky Galore, the 1947 novel by Sir Compton Mackenzie, later made and remade for the big screen.
- f$ ^4 h3 f c$ |$ l. M - * k) M3 ?1 \! A. N
- The story tells of how the locals find their island awash with whisky after a ship loaded with liquor is wrecked off a fictional Scottish island. 6 O3 T5 }0 N! n) D9 q% d4 v/ O
0 F/ [% D9 l+ }, Q$ t/ K1 c- The plot was based on the real-life salvage operations carried out by locals when the SS Politician, carrying 280,000 bottles of malt whisky, ran aground on Eriskay in 1943.
( @4 ^% f1 C* b - / c. k6 _# y; G9 |1 R" E l
- The arrival of the pineapples will be far less lucrative for beachcombers, and not as profitable, either, as the grounding of the cargo ship MSC Napoli off Branscombe beach in Devon in 2007.- R# M" R2 ~) s$ S5 @/ W2 \: L
% T6 f* X, q- v7 m3 o- Then scavengers ignored police advice and arrived in their droves to explore shipping containers, which contained motorbikes, pet food, wine barrels and anti-wrinkle cream." X N w9 k8 u/ y) w
- ''': F% t! i8 H0 F" B1 G! o* A
- ; D9 M- N$ z/ E; \9 b* L
- - ]1 x8 m8 s- K; m/ L. j# Z
- text = ''.join(str).strip().lstrip().rstrip().replace('\n',' ')
) i6 v; j% i4 i6 z T/ Y G - with open('~/text.txt', 'wb') as handle:
+ N- @) ] T7 |8 d - handle.write(text)4 w: O* b8 ~; z3 G! z1 y! H# W
# y- n2 k; n/ m" c$ y% j- str = str.replace('”','"')9 v4 W6 E4 s& W6 G
- str = str.replace('“','"')( D l1 {, h/ f; L; v
- 0 k) c8 x! o X; C H1 i6 c
* {' Z/ n2 ]. R7 P, _- def splitStr(str):4 t$ L2 c* x- P% K* m( o
- arr = str.split(' ')
# Q6 d4 q/ x2 a$ ?7 M3 b" V" k - sz = len(arr)7 ^: a! u- T8 `" K) T( O- I
- return [' '.join(arr[0:sz/2]),' '.join(arr[(sz/2):])]
# l5 `& X: s$ o4 X* n7 |2 a& \ -
9 n: y3 d: F d9 d8 i( Y0 \ O# o) U# o
+ C& C4 g, W& Z6 G8 [- #print splitStr('with wording from North Korea about getting rid of its nuclear weapons and a guarantee from the United States that it would not interfere with the North’s regime or demand redress for human rights abuses.')
- \; R8 @/ j$ M$ M% V - 7 V# r6 S ^% x9 O; ~
- keyArr = []
; w$ [' }5 F: I7 {) v* l% v7 O+ o - sent_tokenize_list = sent_tokenize(str)5 P" D- k% \# P& I
- for s in sent_tokenize_list:
& d) k2 m6 j+ m, A6 g; S% V - sz = len(' '.join(s.split()))
! X( v8 i, B' ~( L! H, o/ H% U - if sz <= 190:
5 b7 }2 z( p% x- e - keyArr.append(' '.join(s.split()))
2 w: t! }0 g( M) m - #print '[ '+' '.join(s.split())+' ]'
_% w0 z3 I0 }& \ - else:
4 l1 J( r) |! c - for ses in s.split(','):
: O: Z# K+ W' _ - if len(ses) > 190:
3 x& N+ X3 H: r( _ - keyArr.extend(splitStr(ses))) n8 n W: @' o2 F8 l. b
- else:4 G9 ?. l3 a j2 ~' `# _) T
- keyArr.append(' '.join(ses.split()))
& u: ]: L% u7 Y3 [
# |. B: M* ^2 T' U- ) X; I1 ^4 i: @. D- ?
- API_URL = "http://translate.google.com/translate_tts?ie=UTF-8&tl=en-us"4 E9 Q) f% z, w6 G* O
- #key = HTMLParser.unescape.__func__(HTMLParser, translate(str,'en'))1 A3 [% t5 a3 n
- #keyArr = sentence_split(str)
, N M% I! B1 n+ U' Z& }! u* M - 9 M( H1 b$ i( j. N: x7 n
, c! Z2 g+ S7 _; x- #print([text[i:i+n] for i in xrange(0, len(text), n)])
' p- `6 F3 u# b5 c - os.system('rm ~/tmp/audio/*.mp3')6 q5 w; F* u# ~
- namei = 0
; x/ r# j- `. t$ _6 R) e1 C - for i in keyArr:
1 |8 I. d& r7 k0 O7 s/ K - juzi = ' '.join(i.split())
( m; U9 g* ?* w& p! A" P - sz = len(juzi)
, U$ \' T! w, D7 s) E1 m' I I( B - link = API_URL+"&q="+juzi+"&client=tw-ob"+ S! @* z% G( O" N0 o% D5 V; K
- print link
8 s! Y+ j3 v' v4 L - path = "~/tmp/audio/%d.mp3" % namei
5 r; l1 F ^: d5 z; [# j - #print path
/ e: {+ ]/ t; V+ u% {# | - DownloadAudio(link,path)3 n( p/ d/ f# {( L5 ~# }+ F2 C4 Q
- os.system('file '+path)
! s S& S! ?$ n5 }0 J - time.sleep(1)
5 l9 H G, `$ E2 R7 `3 h& g( n+ u - namei = namei + 1 m! ^. ]/ C8 e1 ?7 d% h/ Q
复制代码 0 j2 h, \- m$ M8 s
乱七八糟拼一拼 就是个小玩意~~~~~ |