如何使用Spacy统计pandas DataFrame指定列每行的单词数量?
实现步骤
首先安装需要的依赖包、下载spaCy英文模型:
pip install pandas spacy beautifulsoup4 python -m spacy download en_core_web_sm
之后按以下代码处理即可:
import pandas as pd import spacy from bs4 import BeautifulSoup # 加载spaCy模型,禁用不需要的组件提升处理速度 nlp = spacy.load("en_core_web_sm", disable=["parser", "ner"]) # 定义单词计数函数 def count_spacy_words(text): # 去除HTML标签 text_no_html = BeautifulSoup(text, "html.parser").get_text() # 处理文本 doc = nlp(text_no_html.strip()) # 过滤掉标点、空白符号,统计有效单词数量 return len([token for token in doc if not token.is_punct and not token.is_space]) # 构造原数据 data = [['A', '</b> A 1960\'s era\n\n<b>'], ['B', '</b> Yeah, I know.\n'], ['C', '</b> This is a cute cat\n\n<b>']] df = pd.DataFrame(data, columns = ['id', 'text']) # 生成统计列 df['number_of_words'] = df['text'].apply(count_spacy_words)
运行后得到的df和你给出的预期结果完全一致。
如果不想额外安装BeautifulSoup,也可以用正则表达式替换HTML标签,把计数函数里的标签清理逻辑替换为:
import re text_no_html = re.sub(r'</?b>', '', text)
内容的提问来源于stack exchange,提问作者Alina
相关产品推荐
相关产品推荐

