css 如何翻译html文件内容到另一种语言?

sycxhyv7  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(96)

在使用下面的代码,我没有得到准确的格式,因为我得到之前翻译。请指导我哪里我犯了错误。
代码

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"))
rdlzhqv9

rdlzhqv91#

text_elements = [element for element in soup.find_all(string=True) if element.parent.name not in ['script', 'style']]

for element in text_elements:
    # Extract the text from the element
    text = element.get_text(strip=True)
    # Skip the element if it's empty
    if not text:
        continue
    # Translate the text
    translated_text = translator.translate(text, dest='hi')
    # Replace the text in the element
    element.replace_with(translated_text)

相关问题