调用spaCy的nlp方法报错:期望str类型却得到DataFrame如何解决
错误根源
报错出在doc = nlp(review_table)这一行:spaCy的nlp处理管道仅支持传入字符串类型的单条文本,你直接把整个pandas DataFrame对象review_table作为参数传入,触发了类型不匹配的错误。
解决方法
根据你的使用场景选对应方案即可:
方案1:仅测试单条评论的分词效果(匹配你原有测试逻辑)
把nlp的输入改成单条评论的文本即可,假设你存储评论原文的列名为content(如果你的列名不同自行替换):
review_table["exemple"] = [[sent for sent in doc.sents] for doc in review_table["spacy"]] exemple = review_table["exemple"].iloc[0] # 仅传入第一条评论的字符串内容 doc = nlp(review_table["content"].iloc[0]) tokens = [token.text for token in doc] print(exemple,'\n') print(tokens)
方案2:批量处理全表1000条评论生成分词结果
如果需要给所有评论生成分词列,用apply批量处理即可:
# 定义通用分词函数 def parse_tokens(text): doc = nlp(text) return [token.text for token in doc] # 全表批量处理,结果存入新的tokens列 review_table["tokens"] = review_table["content"].apply(parse_tokens) # 查看第一条分词结果验证 print(review_table["tokens"].iloc[0])
额外优化提示
你代码里已经有review_table["spacy"]列,看起来是提前处理好的spaCy Doc对象集合,可以直接从该列提取分词,不需要重复调用nlp浪费算力:
review_table["tokens"] = [[token.text for token in doc] for doc in review_table["spacy"]]
内容的提问来源于stack exchange,提问作者Narin
相关产品推荐
相关产品推荐

