1. 报错信息
ImportError: cannot import name 'AAA' from 'textattack.search_methods'
(/home/666/anaconda3/envs/textattack37_env/lib/python3.7/site-packages/textattack/search_methods/__init__.py)
2. 出错简述
贴一段test1.py的模块导入
#建议使用!
import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
#忽略警告!
import warnings
warnings.filterwarnings("ignore")
#问题出在这!
from textattack.constraints.grammaticality import PartOfSpeech
from textattack.constraints.pre_transformation import (RepeatModification, StopwordModification,)
from textattack.constraints.semantics.sentence_encoders.universal_sentence_encoder import UniversalSentenceEncoder
from textattack.goal_functions import UntargetedClassification
from textattack.search_methods import AAA
from textattack import Attack
import textattack
from textattack.transformations import WordSwapMaskedLMSA
3. 解决方案
出现问题的原因:mytest与textattack是同级目录,mytest里的test1.py找不到外边的textattack模块,所以就用的虚拟环境的textattack!
解决方案1:
把test1.py拿出来,放到与textattack文件夹同级目录,就能正确找到AAA
解决方案2:
考虑不同文件夹之间模块调用,用sys.path.append('../textattack')
from textattack.constraints.grammaticality import PartOfSpeech
from textattack.constraints.pre_transformation import (RepeatModification, StopwordModification,)
from textattack.constraints.semantics.sentence_encoders.universal_sentence_encoder import UniversalSentenceEncoder
from textattack.goal_functions import UntargetedClassification
###########################
#from textattack.search_methods import AAA #原
#### 改
import sys
sys.path.append('../textattack')
from search_methods import SimulatedAnnealnig #search_methods下可能会有红色波浪线
###########################
from textattack import Attack
import textattack
from textattack.transformations import WordSwapMaskedLMSA
第二种方法试过了,需要改动的太多了😭