如何调整列表推导式生成的NLTK词形还原结果的输出格式
问题修正方案
根因说明
- 核心错误1:
nltk.tag.pos_tag仅支持输入分词后的单词列表,直接传入原始字符串会将每个字符、空格都识别为独立处理单元,才会出现单字符拆分的输出结果 - 核心错误2:词形还原后得到的是单词列表,需要手动拼接为空格分隔的字符串才能得到你需要的输出格式
- 遗漏问题:代码中调用了
wordnet但未导入对应模块,运行会触发NameError
完整修正代码
import pandas as pd import nltk from nltk.stem import WordNetLemmatizer # 补全wordnet导入 from nltk.corpus import wordnet # 首次运行需要下载nltk依赖组件,运行一次后可注释 nltk.download('punkt') nltk.download('averaged_perceptron_tagger') nltk.download('wordnet') df = pd.read_csv(r"C:xxxxx") rws=df.loc[:, ['MESSAGE']] # 新增分词步骤,先把文本拆分为单词列表再做词性标注 rws['pos_tags'] = rws['MESSAGE'].apply(lambda x: nltk.tag.pos_tag(nltk.word_tokenize(x))) def get_wordnet_pos(tag): if tag.startswith('J'): return wordnet.ADJ elif tag.startswith('V'): return wordnet.VERB elif tag.startswith('N'): return wordnet.NOUN elif tag.startswith('R'): return wordnet.ADV else: return wordnet.NOUN rws['wordnet_pos'] = rws['pos_tags'].apply(lambda x: [(word, get_wordnet_pos(pos_tag)) for (word, pos_tag) in x]) wnl = WordNetLemmatizer() # 词形还原后用join拼接为空格分隔的字符串 rws['lemmatized'] = rws['wordnet_pos'].apply(lambda x: ' '.join([wnl.lemmatize(word,tag) for word,tag in x]))
内容的提问来源于stack exchange,提问作者Louise
相关产品推荐
相关产品推荐

