我试图调用包dictionary
中模块dict.py
中的函数is_english_word
。以下是层次结构:
DataCleaning
|___ text_cleaner.py
|___ dictionary
|___ dict.py
|___ list_of_english_words.txt
为了澄清,我在一个名为dictionary
的包中有dict.py
和list_of_english_words.txt
。你知道吗
以下是用text_cleaner.py
编写的import语句:
import DataCleaning.dictionary.dict as dictionary
下面是用dict.py
编写的代码:
import os
with open(os.path.join(os.path.dirname(os.path.realpath('__file__')), 'list_of_english_words.txt')) as word_file:
english_words = set(word.strip().lower() for word in word_file)
def is_english_word(word):
return word.lower() in english_words
但是当我运行text_cleaner.py
文件时,它显示了一个导入错误,因为它找不到list_of_english_words.txt
:
Traceback (most recent call last):
File "E:/Analytics Practice/Social Media Analytics/analyticsPlatform/DataCleaning/text_cleaner.py", line 1, in <module>
import DataCleaning.dictionary.dict as dictionary
File "E:\Analytics Practice\Social Media Analytics\analyticsPlatform\DataCleaning\dictionary\dict.py", line 3, in <module>
with open(os.path.join(os.path.dirname(os.path.realpath('__file__')), 'list_of_english_words.txt')) as word_file:
FileNotFoundError: [Errno 2] No such file or directory: 'E:\\Analytics Practice\\Social Media Analytics\\analyticsPlatform\\DataCleaning\\list_of_english_words.txt'
但是当我运行dict.py
代码本身时,它没有显示任何错误。我可以清楚地看到os.path.dirname(os.path.realpath('__file__'))
指向text_cleaner.py
的目录,而不是dict.py
。如何使模块dict.py
的导入独立于调用它的位置?你知道吗
问题是您将字符串
'__file__'
传递给os.path.realpath
,而不是变量__file__
。你知道吗更改:
收件人:
相关问题 更多 >
编程相关推荐