FileNotFoundError:[Errno 2]没有这样的文件或目录:“f”

2024-04-25 22:30:20 发布

您现在位置:Python中文网/ 问答频道 /正文

请原谅我无知的问题。 我正处于学习Python的婴儿阶段。 我想将前\u文本转换为后\u文本

<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!

事实上,不管代码是什么,我只需要得到这个结果(在_文本之后)。 我使用了以下代码:

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'

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


Tags: 代码in文本selfinputreadlineifsys
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

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

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

相关问题 更多 >