python - 如何使用预定义列表中的单词出现在数据框的文本列中的次数的计数器创建一个新列?
问题描述
我想构建一个新列,其中包含 ai_functional 列表中的单词在文本列中出现的次数的计数。
给出的清单是:
> ai_functional = ["natural language
> processing","nlp","A I ","Aritificial intelligence", "stemming","lemmatization","lemmatization","information
> extraction","text mining","text analytics","data-mining"]
我想要的结果如下:
> text counter
>
> 1. More details A I Artificial Intelligence 2
> 2. NLP works very well these days 1
> 3. receiving information at the right time 1
我一直在使用的代码是
def func(stringans):
for x in ai_tech:
count = stringans.count(x)
return count
df['counter']=df['text'].apply(func)
请有人可以帮我解决这个问题。我真的被卡住了,因为每次我应用这个我都会在计数器列中得到结果为 0
解决方案
当你这样做count =
时,你删除了以前的值,你想总结不同的计数
def func(stringans):
count = 0
for x in ai_tech:
count += stringans.count(x)
return count
# with sum and generator
def func(stringans):
return sum(stringans.count(x) for x in ai_tech)
修复了一些拼写错误ai_tech
并将所有设置.lower()
为计数器 col 中的给定2,1,0
,最后一行没有共同值
import pandas as pd
ai_tech = ["natural language processing", "nlp", "A I ", "Artificial intelligence",
"stemming", "lemmatization", "information extraction",
"text mining", "text analytics", "data - mining"]
df = pd.DataFrame([["1. More details A I Artificial Intelligence"], ["2. NLP works very well these days"],
["3. receiving information at the right time"]], columns=["text"])
def func(stringans):
return sum(stringans.lower().count(x.lower()) for x in ai_tech)
df['counter'] = df['text'].apply(func)
print(df)
# ------------------
text counter
0 1. More details A I Artificial Intelligence 2
1 2. NLP works very well these days 1
2 3. receiving information at the right time 0
推荐阅读
- hibernate - 如何防止在 Spring Boot 中自动生成 @UpdateTimestamp
- image - 如何从 Batflat CMS 中仅发出图库 IMG
- typescript - 全局变量在 HTTP 调用中变得未定义
- mysql - Mysql 查询错误:SELECT 列表不在 GROUP BY 子句中且包含非聚合列,与 sql_mode=only_full_group_by 不兼容
- verilog - Verilog 模块未按预期更新
- python - 需要更高效的代码来编写一级矩阵的总和
- python - 如何读取 SVG 文件并在其中绘制内容?
- mysql - MySQL中的模糊名称搜索,匹配相关性
- dns - 如何使用安装在 Digital Ocean VPS 上的 Direct Admin 解析域
- android-studio - Gradle 错误:路径不是保存在 OneDrive 中的 Android 项目的可读目录