如何在命令行中使用嵌入的文本文件运行Python脚本?
在那里。我为这个简单的问题道歉,但我是一个完全的新手,需要一些帮助。我正在试着运行彼得·诺维格的拼写更正器(http://norvig.com/spell.py),但我收到的答复如下:如何在命令行中使用嵌入的文本文件运行Python脚本?,python,file,Python,File,在那里。我为这个简单的问题道歉,但我是一个完全的新手,需要一些帮助。我正在试着运行彼得·诺维格的拼写更正器(http://norvig.com/spell.py),但我收到的答复如下: C:\>spelling.py Traceback (most recent call last): File "C:\Python27\spelling.py", line 11, in <module> NWORDS = train(words(file('big.txt').r
C:\>spelling.py
Traceback (most recent call last):
File "C:\Python27\spelling.py", line 11, in <module>
NWORDS = train(words(file('big.txt').read()))
IOError: [Errno 2] No such file or directory: 'big.txt'
C:\>spelling.py
回溯(最近一次呼叫最后一次):
文件“C:\Python27\spelling.py”,第11行,在
NWORDS=train(单词(文件('big.txt').read())
IOError:[Errno 2]没有这样的文件或目录:“big.txt”
该脚本包含一个嵌入的文本文件(big.txt),我创建了该文件并将其保存在与spelling.py相同的目录中。为什么找不到大的.txt文件?
其次,一旦脚本开始工作,我将如何针对需要更正的单词样本使用它?脚本的工作目录是当前文件夹,而不是脚本的文件夹 您可以向脚本中添加以下代码来更改此设置:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
当然,您也可以仅在打开文件时使用此文件夹,而不是更改工作目录:
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'big.txt')
NWORDS = train(words(file(path).read()))
脚本的工作目录是当前文件夹,而不是脚本的文件夹 您可以向脚本中添加以下代码来更改此设置:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
当然,您也可以仅在打开文件时使用此文件夹,而不是更改工作目录:
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'big.txt')
NWORDS = train(words(file(path).read()))