【问题标题】:FileNotFoundError: [Errno 2] No such file or directory: '-f'FileNotFoundError:[Errno 2] 没有这样的文件或目录:'-f'
【发布时间】:2021-08-24 07:03:57
【问题描述】:

请原谅我无知的问题。 我正处于学习 Python 的初级阶段。 我想将 Before_text 转换为 After_text。

<Before_text>
Today, I got up early, so I’m absolutely exhausted. I had breakfast: two slices \n
of cold toast and a disgusting coffee, then I left the house at 8 o’clock still \n
feeling half asleep. Honestly, London’s killing me!
<After_text>
Today, I got up early, so I’m absolutely exhausted. 
I had breakfast: two slices of cold toast and a disgusting coffee, then I left the house at 8 o’clock still feeling half asleep. 
Honestly, London’s killing me!

其实不管代码,我只需要得到这个结果(After_text)。 我使用了这段代码:

import sys, fileinput
from nltk.tokenize import sent_tokenize

if __name__ == "__main__":
    buf = []

    for line in fileinput.input():
        if line.strip() != "":
            buf += [line.strip()]
            sentences = sent_tokenize(" ".join(buf))

            if len(sentences) > 1:
                buf = sentences[1:]

                sys.stdout.write(sentences[0] + '\n')

    sys.stdout.write(" ".join(buf) + "\n")

产生以下错误:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-1-ef8b2fcb97ad> in <module>()
      5     buf = []
      6 
----> 7     for line in fileinput.input():
      8         if line.strip() != "":
      9             buf += [line.strip()]

-------------------------1 frames--------------------------------------------------
/usr/lib/python3.7/fileinput.py in _readline(self)
    362                     self._file = self._openhook(self._filename, self._mode)
    363                 else:
--> 364                     self._file = open(self._filename, self._mode)
    365         self._readline = self._file.readline  # hide FileInput._readline
    366         return self._readline()

FileNotFoundError: [Errno 2] No such file or directory: '-f'

是什么导致了这个错误?此代码中的错误在哪里? 以及如何以及在何处加载和保存文本文件? 请教我~

【问题讨论】:

  • 您可以做的是读取文件并使用 for 循环遍历行
  • 看起来你用来运行这个程序的命令行包含&lt; -f,意思是“从名为-f的文件中获取输入”,但没有这样的文件。你的意思是不是像&lt; myfile.txt

标签: python file-io nltk tokenize


【解决方案1】:

根据文档,fileinput.input() 是一种从命令行输入获取内容并尝试一次打开一个的快捷方式,或者如果未指定任何内容,则使用 stdin 作为其输入。

请告诉我们您是如何调用脚本的。我怀疑你那里有一个-f,该函数正在尝试打开。

【讨论】:

    【解决方案2】:

    如果你想使用fileinput.input(),你应该提供输入文件名作为参数(sys.argv),简单的例子,如果你有cat.py如下

    import fileinput
    for line in fileinput.input():
        print(line, end='')
    

    和文本文件file1.txtfile2.txtfile3.txt在同一目录中,那么用法是:

    python cat.py file1.txt file2.txt file3.txt
    

    【讨论】:

    • 我真的不需要上面的主要代码。我只需要这些。 1. 加载一个文本文件。 2. 删除行尾的所有换行符并重新连接它们。 3. 新句子以新行开头。 4. 保存翻译好的文本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 2021-03-07
    • 2015-06-09
    • 2021-04-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多