1

I would like to automatically pre-translate a bunch of text files that I have on my hard disk. Is there a way to do this with python. I already got the google translate api key and I would like to use that. The files I have include some XML code, however, I first would like to get the translator to work with some plain text files. One text file might look like this:

Hello, my name is Stefan. I live in Germany and my hobbies are tennis, walking and reading.

My question now is how to read in the text file and automatically translate it from English to German.

I looked around the web for quite a while but I couldn't find a solution to my problem.

Any direct help or linkage to another post/website is greatly appreciated.

Daenyth
  • 35,856
  • 13
  • 85
  • 124
Strohmi
  • 523
  • 5
  • 21

2 Answers2

0

If you want to look at a parse question I answered which is Perl not Python, this is part of a program that parses HTML to extract strings before sending them to the Bing translator. You'll need to do something like that with the XML probably via a Python parsing library.

Then you call the translator service on the string:

   # minor adjustment for simplified chinese....
    my $call_language = $language;
    $call_language =~ s/zh/zh-CHS/;

    # microsoft application id for translator....
    my $appId = 'blablabla';
    my $url =
"http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=$appId&text=$text&from=en&to=$call_language";

    ###my $url = "https://www.googleapis.com/language/translate/v2?key=<my-key>&q=$text%20world&source=en&target=$language" ;
    # Create a request
    my $req = HTTP::Request->new( GET => $url );

    # Pass request to the user agent and get a response back
    my $res = $ua->request($req);

    #sleep 2 ;
    # Check the outcome of the response
    if ( $res->is_success ) {
        $content = $res->content;

Again that's Perl but it gives you the idea, I hope...

Community
  • 1
  • 1
Hugh Barnard
  • 352
  • 2
  • 12
0

The Google Translate API is now a pay service only, probably because a lot of people were trolling huge amounts of data off through it. Effectively it's a RESTful API, which means you use standard url and json tools to produce a query in HTTP and then hand that to the API as a GET and then you'll receive back a json object with your translation. Effectively you'd read in your source file, assemble it into a query, send the HTTP GET of yout query to Google, then parse and use the response.

michaelfilms
  • 704
  • 3
  • 5