2

I'm seeking to run googletrans to translate a series of 300 .txt files in a single folder. I'm struggling to construct a loop that will allow me to run a translation of each file and write the output in new .txt files. Googletrans has a limit on bulk translations, so I'm happy to limit the iterations to 50 files at a time.

Here's the code for translating a single file. It prints the original txt file, then the translated file, and finally outputs the file into a new txt file.

from googletrans import Translator

f = open('Translation Project\page_323.txt', 'r')

if f.mode == 'r':
    contents = f.read()
    print(contents)

translator = Translator()
result = translator.translate(contents, dest='en')
print(result.text)

with open('Translation Project\trans_page_323.txt', 'w') as f:
    f.write(result.text) 

Any thoughts? New to Python and still wrapping my head around loops.

6
  • This looks great, but may be a question for Code Review Stack Exchange. What question are you asking? Are you asking how to make this into a loop, or are you asking if this would work? Commented Apr 28, 2021 at 22:11
  • Thanks for the assistance and advice. I'm asking how to make this into a loop. Commented Apr 28, 2021 at 22:19
  • Are the file names formatted as trans_page_1.txt or trans_page_001.txt? Also, what is the max page number? Commented Apr 28, 2021 at 22:21
  • Also, it may help to edit the question to make that a bit more clear :-) Commented Apr 28, 2021 at 22:21
  • 1
    Happy to do so - working on earning reputation to upvote! Thanks again. Commented Apr 29, 2021 at 0:04

1 Answer 1

2

Assuming that there are 999 pages, the files are formatted as trans_page_1.txt rather than trans_page_001.txt, and that the first page is page 1, not page 0:

from googletrans import Translator
translator = Translator()

for page_number in range(1, 999):

    f = open(f'Translation Project\page_{page_number}.txt', 'r')

    if f.mode == 'r':
        contents = f.read()
        print(contents)


    result = translator.translate(contents, dest='en')
    print(result.text)

    with open(f'Translation Project\trans_page_{page_number}.txt', 'w') as f:
        f.write(result.text)

This doesn't limit the files translated, but you can do this by changing the maximum page to 50 or by doing some other code shenanigans.

Sign up to request clarification or add additional context in comments.

1 Comment

Solved! Thank you very much for the assistance, and patience working through my lack of clarity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.