|
发表于 2020-7-20 20:12:52
|
显示全部楼层
2 f/ D9 [6 D$ y- # -*- coding: UTF-8 -*-9 h, F6 e9 w" P5 o1 n
- import requests
9 i7 U- b4 c1 [ - import os
; Q! V# O& F }/ a- w6 U - import subprocess- H' B1 T ?6 A& ^' B0 b7 n( e5 v
- import sys
7 l. q" b: z3 | - from tqdm import tqdm4 T8 o J$ y+ J# Z5 _
- import time,random7 J1 y8 Y: h' g5 Y; y
- from HTMLParser import HTMLParser
$ U. a; S* ~7 m. j - import sys
* L! j0 e* j- e7 u# p - reload(sys)
$ v v3 W# @2 ]) C2 q$ I - sys.setdefaultencoding('utf8')
0 y" ^: f* I. Y0 G
) M6 T0 b" L1 x5 S3 Y# E' S* V- class WebRequest(object):# a2 c. w9 i/ r9 E" G: A1 \5 ~
- def __init__(self, *args, **kwargs):
$ B5 Z# U" p0 [$ D6 S - pass
- e% N) @3 \6 @! `1 X. \ - ( o* F c: i6 V: T+ D3 g* s
- @property
% ^9 Q3 U/ f2 R4 J, C$ ^- V# v - def user_agent(self):
8 @* Q" {8 D4 Y, w$ X* G - """
. |5 @1 b+ p3 R# ]; x9 a* u: ]* h. L: { - return an User-Agent at random
) @, J" ?: v# ^$ m0 z. d9 ` - :return:
! k" {1 W0 \9 _( D$ M4 A - """7 k9 G8 P2 j$ R4 o4 J7 O
- ua_list = [
) Z) ?, l5 [3 R8 f2 D4 d3 p - 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101',
) S" H- C" H6 ]& X+ q0 G - 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122',9 n- L" j+ Q& J: D* ]' V% }, v4 A
- 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71',- O# K8 G4 r) s: ?# n
- 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95',
; N1 P: X+ V) P4 W# w5 U - 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71',5 Z; P& K' f$ @) k% H6 h
- 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)'," d7 O3 j( G9 F4 J+ \3 y
- 'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50',
4 Q* |. A r/ _ - 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0',
k! }- Q$ h1 h6 Z G0 I. ? p - ]* u0 {3 h/ ] A4 Z
- return random.choice(ua_list)
7 s0 s3 s& ?" G$ A7 K$ S
' N3 J/ Y$ q" K$ M5 r- @property
& i( G2 @$ a0 }1 @$ } - def header(self):
" ^$ D7 ?4 ~ c4 i* n - """
& F/ \) O" ?$ O5 n - basic header2 k# \# q7 ^8 }6 }
- :return:$ u1 ~3 J% ^/ n; p
- """# j% J K; P& q5 y. ]- P9 Q1 }& d
- return {'User-Agent': self.user_agent," N& w+ i6 S( i- e* s! r
- 'Accept': '*/*',
^' m9 b" ]! U2 _4 G* t - 'Connection': 'keep-alive',3 K* R" }% i9 k& y+ ^3 D" F
- 'Accept-Language': 'zh-CN,zh;q=0.8'}
: c5 s7 ]5 Y; `- ?* C
6 e' Q5 e1 r& K: U1 T3 M) o- def get(self, url, header=None, retry_time=5, timeout=30,- ~5 E9 g& R8 q3 u+ d$ L5 t
- retry_flag=list(), retry_interval=5, *args, **kwargs):) F- d+ c" M- k' ^& A1 O9 w
- """7 x1 R1 z0 a$ A9 M: H2 ~
- get method
3 R8 B4 M; L; n# { v E - :param url: target url
7 f1 Z" y. e) k( H4 ^ - :param header: headers
8 d: W9 h3 `' l5 x! f+ z/ \ - :param retry_time: retry time when network error% n, b' r8 n s8 |
- :param timeout: network timeout
$ A3 r( [0 O. l3 ] - :param retry_flag: if retry_flag in content. do retry
4 i- ^. a' d. Z0 N1 Z+ u) M6 w1 d - :param retry_interval: retry interval(second): s) G( y4 z& n- ^
- :param args:
6 F: f! [9 P3 N6 f: t) j! C - :param kwargs:, h$ `5 N' t- F g: e V
- :return:& T# z( K: f8 W) [, k) Q
- """
6 Z, e) H/ [7 Q4 h5 g6 _. J - headers = self.header0 v, v9 k. B/ Z/ Y; U0 {3 l. `% [4 ~$ D
- if header and isinstance(header, dict):
$ d% i" H& f+ Z/ ~) F5 ]. Y1 O - headers.update(header)
4 h- P* E! H% l7 z4 |# G, ~ - while True:
/ E9 Z, ]6 I9 |8 l* t3 c - try:& \# f! Q: Z+ }. o1 i
- html = requests.get(url, headers=headers, timeout=timeout, stream=True)6 S% ]* V, _' E6 W) r
- print 'content size: %d' % len(html.content)3 h4 K1 ~) c+ g3 l( B
- if any(f in html.content for f in retry_flag):) Q0 Z) k% E7 Y! o1 N) E7 E3 B, ]
- raise Exception/ n, O# y6 \ O5 h) g
- if not html.content:8 `$ e" D" t' \ O/ I6 P* O
- print 'content is Null,retry...~' + url6 V/ k M9 a3 X6 i6 b3 w% c; w8 F
- raise Exception
$ _0 T% F( i7 J% G& s - return html; c, Y) y) H$ x2 w6 y8 [
- except Exception as e:& G T4 F* ~6 b
- print(e); I) i- G# h1 v( O$ @+ C" h
- 0 f5 X6 y% C' Q! [ M
- ; `9 Q/ d0 @" ?9 J7 s
- def DownloadAudio(url, path, refer=None):( e) M. \; N) r( i! m3 e
- with open(path, 'wb') as handle:
' E X* i H* M4 i2 U* A& _2 S - if refer:
' n4 |5 W1 M+ d/ K' c: Y; {4 @ - hdr = {
8 b' w7 K8 G; M# ? - 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',# f6 {! N& T( _5 f% ?. r
- 'Referer': refer}
. p1 [( x: i2 N: p - else:' t! R! n) q- ^8 r2 M
- hdr = {( R8 Y: u0 I d& C' B% S3 U$ h5 N: z2 ~
- 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
8 r- P! ?& w- \) P' e( m4 y - 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
H" J/ |3 j4 d8 J - 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
+ o( |/ v J# d0 a4 m - 'Accept-Encoding': 'none',
1 a3 J4 u; Q% G4 U h! z: ^ - 'Accept-Language': 'en-US,en;q=0.8',, l/ X, N8 w& y. Q, T3 Z. ]1 B2 O1 k
- 'Connection': 'keep-alive'}
, }$ N: |) P3 G% k - wr = WebRequest()! |. T- y- f) S. j5 V6 q0 B
- #print hdr
4 o, L' ~- P- w% d) R3 L - response = wr.get(url,header=hdr)
8 V9 c6 k$ g) v0 y# F - #html = requests.get('https://www.example.com', proxies={"http": "http://{}".format(p!r!o!x!y)})
! q. t! V" V% S# _# H - #response = requests.get(url, stream=True, headers={'User-agent': 'Mozilla/5.0'})3 f' v6 M2 X7 m( f$ s
- #print url
1 W! h& S; w( ?5 i; S2 L: _ - for block in tqdm(response.iter_content(),ascii=True, desc='ImageDownload'):1 }$ {) O4 \; L) |# i9 t3 I1 p: g
- if not block:2 l5 h# G9 J; H( }
- break% ]9 j ~$ q }
- handle.write(block); I/ e7 V5 L7 H3 b. d" `% a
- " q* L5 }6 |0 K2 b
- def translate(to_translate, to_langage="auto", langage="auto"):
" d9 V$ ]5 W7 a, M7 {7 p# P0 a - '''Return the translation using google translate
9 w( p' T6 K5 p! U! ~9 j - you must shortcut the langage you define (French = fr, English = en, Spanish = es, etc...). u" C# @- F3 D
- if you don't define anything it will detect it or use english by default4 E5 N. w& N/ N+ c/ W
- Example: z. d+ T9 U2 u5 ]
- print(translate("salut tu vas bien?", "en"))6 j; V. _5 n. S
- hello you alright?'''3 D$ y3 }, G7 o8 |9 p3 n! t
- 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)"}
% E/ Y4 G. c. w( [. o* G - before_trans = 'class="t0">'
5 p% Y, S4 K' p; [ - link = "http://translate.google.com/m?ie=UTF-8&hl=%s&sl=%s&q=%s" % (to_langage, langage, to_translate.replace(" ", "+"))
. M& z* `+ |$ j' R - request = requests.get(link, headers=agents)
+ F: _% I) ~- b/ V [/ Z/ Z+ P! ^ - page = request.content H& T5 A( Q6 ?( @1 {& ~+ l
- #print page# K" y: j' `2 K) f) K7 q
- result = page[page.find(before_trans)+len(before_trans):]- P) ^, I7 o& k. A7 A. H$ z
- result = result.split("<")[0]1 A- D. s, J; J1 A6 F
- return result3 Y' }( A+ B/ e r9 g
- 2 y3 f( Y. I8 g: O) { p
- tsxt_sen = []
2 T2 a; k% C0 ]0 m2 z1 N. | m/ \1 ] - from nltk.tokenize import sent_tokenize. u) j5 A, z9 G+ _- A% x
- def sentence_split(sentence): # 编写分句函数- t' f, V5 h+ B" r1 A
- text_sen = []; k1 }: s2 e% j7 s, _ O7 z
- for s in sentence.split(','):; n8 f8 N2 U6 a! _1 {! o
- # if '?' in s:, U; ^( L* b3 u* [2 ]- D
- # tsxt_sen.extend(s.split('?'))
7 z# i( ^* b9 x1 u - # elif ',' in s:% [% u1 v# n7 m+ @
- # tsxt_sen.extend(s.split(','))
/ {4 A, x' N' X% j - # else:2 J! l$ v6 F, v: O' @# l9 x" [
- text_sen.append(s)4 A, z b8 A0 t/ t$ t8 ^ \" m9 E: O
- return tsxt_sen" }' H) }0 b# Q6 b+ o. K7 S
- ) L) c( \1 Y4 i; m5 s6 `
- 4 `, Z0 E( Z+ z) W d; G ], l2 m
- str = '''! o& A! L$ y+ J& e4 J B- S% }2 Q
- 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.& W: d# F& ?" g7 k) \) |
/ @% s0 B6 V! A, R3 x0 N- 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.
" ~. i- R8 b# S9 _" T
! ]0 {/ A' S3 _4 [8 H! A) ?3 i- 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.% ^' i' E! @. F- c- {- v
- ( K' f G8 m5 w: R
- 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.
5 P, i* b" f$ V+ {: y8 J
& U/ l1 ^1 E! j, N0 h6 i8 P- 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.
- T: K% Y4 ], d" A: M: r - " y* l# S2 t& G6 W t
- 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.6 N5 q5 A' w9 Y9 P2 w2 F
- }" N, u1 S2 x; B- 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.' O2 J; p3 a6 e( u
- '''* P& a/ d/ D% u& `" V9 `% y
- ; \2 I6 J. U; w, S
- , t$ o7 f% J7 j! W; X: b
- text = ''.join(str).strip().lstrip().rstrip().replace('\n',' ')
. }1 R! H3 V. ]: K - with open('~/text.txt', 'wb') as handle:
7 |: a4 S! Y3 a! H, [+ `3 C, y - handle.write(text)$ A- p& Z, T9 c, Y' }0 s
4 w [/ K6 [1 m; g( Q# i- str = str.replace('”','"')
4 e: _( B$ G- }5 U. ~ - str = str.replace('“','"')
, J: P8 c. ]+ D: N) O0 b9 Y+ o
/ Z/ |: p5 J4 k' r
% U' @$ [" q. x( x9 t' P- def splitStr(str):# r) u- e! o* G8 M$ h, r0 Z
- arr = str.split(' '): [$ f, h' W! E+ X8 e/ z
- sz = len(arr)
8 ` g g. g; u8 [: g6 S - return [' '.join(arr[0:sz/2]),' '.join(arr[(sz/2):])]8 [" V6 x. {: }$ L. o8 O
-
2 y( [3 b. l6 N$ p - 8 n; L; I4 K+ U7 ]* g1 e! x
- #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.')
# b! O% l' L) c# Q+ ~
4 U8 ^" Y; h/ P5 o' k- X0 g$ x- keyArr = []" F! U5 j% {. g& i O
- sent_tokenize_list = sent_tokenize(str)
& M" @! d% C8 t8 \5 s - for s in sent_tokenize_list:. F0 `- [1 X+ x% _4 A
- sz = len(' '.join(s.split()))
. R( h: b" E9 M( \6 T - if sz <= 190:! a- Z$ P5 q/ K2 z; e
- keyArr.append(' '.join(s.split()))
6 B ?# u, b2 z! U% B9 i" o* h - #print '[ '+' '.join(s.split())+' ]'
7 D, T0 n7 Q: z0 ^; \8 ~. g+ d - else:# m5 `: U; l# M# [" E2 i
- for ses in s.split(','):
$ g* h7 ?0 R9 B4 e* s - if len(ses) > 190:; R1 |6 }3 ?, i0 p+ q; Q
- keyArr.extend(splitStr(ses))
3 M; B/ q' F' o& i( J; S/ U- `9 } - else:: f2 Q' M5 N- \! N+ C7 W* H
- keyArr.append(' '.join(ses.split()))
( v, v3 T) q% o8 m3 L, m - 2 }; e" l. V3 m3 C- i
6 t1 o# S& F! e6 B- API_URL = "http://translate.google.com/translate_tts?ie=UTF-8&tl=en-us"8 |- \; \& V( P' ^; ]
- #key = HTMLParser.unescape.__func__(HTMLParser, translate(str,'en'))
. Y3 {8 G+ H$ ~2 ?+ y# g0 L" {: v - #keyArr = sentence_split(str)
' a( D8 Y/ T l1 S0 C5 W3 P -
$ ^8 {. A$ k7 A" q1 i
( P5 x4 j: V$ q- \1 o- #print([text[i:i+n] for i in xrange(0, len(text), n)])
3 t) L) Q2 X* m, @- n9 b: ? - os.system('rm ~/tmp/audio/*.mp3')
8 r. x) s4 b ?, | c2 k2 ? - namei = 0
9 y$ U; e3 r& D |2 K: ^) O0 J - for i in keyArr:: o0 t: m' w1 @3 x- z
- juzi = ' '.join(i.split())5 ?$ S9 F& F$ X; b+ p& j3 I
- sz = len(juzi)
' @' d/ {- J% Q& B$ K - link = API_URL+"&q="+juzi+"&client=tw-ob"
" ]: B. D* n$ n' K - print link; d3 b6 f, I, E/ S' Y
- path = "~/tmp/audio/%d.mp3" % namei: N8 ?9 G, l& h3 V. q
- #print path+ ~) B- x* i n& t- b1 ]+ G' Y
- DownloadAudio(link,path)
# m4 X9 V0 ?, ]' o) w1 ^# t - os.system('file '+path)
* d8 g! `+ q' ?' D! ]! l - time.sleep(1)# m$ b# X6 |/ e8 ?1 Z
- namei = namei + 1" s" S. c3 B& u. o* c" Z6 |: ~0 i6 }
复制代码 |
|