【问题标题】:OSError: [Errno 22] Invalid argument while opening a fileOSError:[Errno 22] 打开文件时参数无效
【发布时间】:2021-07-25 11:56:17
【问题描述】:

我目前正在开发一个应用程序,它逐行翻译输入文件并将翻译后的行写入输出文件,但在运行我的脚本时出现以下错误:OSError: [Errno 22] Invalid argument: '{parent_id:opynw1, body: my text'

完整的错误信息:

Traceback (most recent call last):
  File "test.py", line 12, in <module>
    column1= GoogleTranslator(source='german', target='english').translate_file(row)
  File "C:\Users\supre\anaconda3\envs\test\lib\site-packages\deep_translator\google_trans.py", line 136, in translate_file
    raise e
  File "C:\Users\supre\anaconda3\envs\test\lib\site-packages\deep_translator\google_trans.py", line 132, in translate_file
    with open(path) as f:
OSError: [Errno 22] Invalid argument: '{parent_id:opynw1, body: my text'

我的输入文本文件的内容:

{parent_id:opynw1, body: my text}
{parent_id:h68dhu3, body: my text}
{parent_id:opynw1, body: my text}

我的代码:

from deep_translator import GoogleTranslator

output_file = open('./test.txt', 'w',encoding='utf-8')
reader = open('./data.txt', 'r', encoding='utf-8')
for row in reader:
    column1= GoogleTranslator(source='english', target='german').translate_file(row)
    output_text = str(column1)
    output_file.write(output_text + '\n')
output_file.close()

我的脚本有问题吗?如果是这样,如果有人能告诉我我做错了什么并帮助我解决这个问题,我会很高兴:)

提前感谢您的每一个帮助和建议:)

【问题讨论】:

  • translate_file() 期望参数是文件名。输入文件的行不是文件名。
  • ooo ok 明白了:) 感谢您的快速响应:) 你知道如何解决这个错误吗?
  • 你想做什么?
  • 我想翻译一个大文件,但翻译器每次翻译只允许 5k 个字符。所以我的计划是逐行翻译文件,不超过 5k 个字符的限制。

标签: python python-3.x file


【解决方案1】:

使用translate() 而不是translate_file(),因为该行不是文件名。

您还需要使用ast.literal_eval() 将其解析为字典。

from deep_translator import GoogleTranslator
import ast

with open('./test.txt', 'w',encoding='utf-8') as output_file, open('./data.txt', 'r', encoding='utf-8') as reader:
    for row in reader:
        d = ast.literal_eval(row)
        column1= GoogleTranslator(source='english', target='german').translate(d['body'])
        output_text = str(column1)
        output_file.write(output_text + '\n')

【讨论】:

  • 非常感谢 Barmar :) 这段代码为我修复了它:)
猜你喜欢
  • 2020-01-16
  • 1970-01-01
  • 2019-04-27
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
相关资源
最近更新 更多