运行Python情感分析代码触发KeyError: 1 错误排查求助
问题根因定位
你遇到的KeyError: 1报错,根源是pos_after_negator函数中使用row[1]访问行数据的写法不兼容你当前使用的pandas版本。
你构造的nnn_words DataFrame列名为0、idx、words,用axis=1调用apply时,传入函数的row是带列名索引的Series对象,使用整数1作为索引访问时,pandas会优先匹配名为1的列,而该列不存在,就触发KeyError。
修复方案
核心修复(必改)
把pos_after_negator函数中所有的row[1]替换为列名访问或者显式位置访问即可,推荐用列名访问,可读性更高也不会受版本影响:
def pos_after_negator(row,pos,file_content_tokenized): string = row['words'] # 所有row[1]替换为row['idx'] next1 = file_content_tokenized.get(row['idx']+1,'') string += ' ' + str(next1) if next1 in pos: return string next2 = file_content_tokenized.get(row['idx']+2,'') string += ' ' + str(next2) if next2 in pos: return string next3 = file_content_tokenized.get(row['idx']+3,'') string += ' ' + str(next3) if next3 in pos: return string return None
如果需要保留位置访问的写法,也可以将row[1]改为row.iloc[1],显式指定按位置取值。
其他可优化问题(可选改)
- 代码中读文件存在重复打开的问题:你已经用
with open(file, 'r') as myfile打开了文件,直接用file_content = myfile.read()读取即可,不需要再单独调用一次open(file, 'r').read() - 路径拼接建议使用
os.path.join(path, file),避免手动拼接路径分隔符出现适配问题 - 新版本pandas已经弃用
Series.append方法,可以先把结果存在普通list中,循环结束后再统一转为Series,避免运行警告
内容的提问来源于stack exchange,提问作者Ciel Meow
相关产品推荐
相关产品推荐

