简体   繁体   English

如何将 html 文件内容翻译成另一种语言?

[英]how to translate html file contents into another language?

On using the below code I was not getting the exact formatting as I got before translating.在使用下面的代码时,我没有得到我在翻译之前得到的确切格式。 Please guide me where I am making mistakes.请指导我在哪里犯错误。

Code代码

from googletrans import Translator
from bs4 import BeautifulSoup, Tag,NavigableString
html = open("data.html").read()
soup = BeautifulSoup(html)
tags = soup.find_all(["p","ul","ol","h1","h2","h3","h4","h5","h6","td"])
translator=Translator()
def callcon(t, tag):
  for i in range(0, len(t)):
    if type(t[i])== NavigableString:
      #print(t[i])
      translation=translator.translate(t[i],dest="hi").text
      new_text = tag.find(text=str(t[i])).replace_with(translation)
      #print(new_text)
      #og=og.replace(str(t[i]),"suneri")
      #return og
    else:
      #print(t[i].contents)
      #print(og)
      callcon(t[i].contents,tag)
for tag in tags:
  #constr="".join(str(e) for e in tag.contents)
  #print(constr)
  callcon(tag.contents, tag)
with open("output2.html", "wb") as f_output:
    f_output.write(soup.prettify("utf-8"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM