【发布时间】:2020-12-14 21:28:45
【问题描述】:
我是 Python 和 nltk 的新手,因此非常感谢您对以下问题的意见。
目标:
我想搜索并计算存储在 pandas DataFrame 中的标记化句子中特定术语的出现次数。我正在搜索的术语存储在字符串列表中。输出应保存在新列中。
由于我要搜索的词在语法上是变形的(例如,猫而不是猫),我需要一个不仅显示完全匹配的解决方案。我想对数据进行词干化并搜索特定词干是一种合适的方法,但我们假设这不是一个选择,因为我们仍然会有语义重叠。
到目前为止我尝试了什么:
为了进一步处理数据,我按照以下步骤对数据进行了预处理:
- 全部小写
- 删除标点符号
- 标记化
- 删除停用词
我尝试使用str.count('cat') 搜索单个术语,但这并不能解决问题,并且使用NaN 将数据标记为缺失。此外,我不知道如何在使用 pandas 时以有效的方式迭代搜索词列表。
到目前为止我的代码:
import numpy as np
import pandas as pd
import re
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
# Function to remove punctuation
def remove_punctuation(text):
return re.sub(r'[^\w\s]','',text)
# Target data where strings should be searched and counted
data = {'txt_body': ['Ab likes dogs.', 'Bc likes cats.',
'De likes cats and dogs.', 'Fg likes cats, dogs and cows.',
'Hi has two grey cats, a brown cat and two dogs.']}
df = pd.DataFrame(data=data)
# Search words stored in a list of strings
search_words = ['dog', 'cat', 'cow']
# Store stopwords from nltk.corpus
stop_words = set(stopwords.words('english'))
# Data preprocessing
df['txt_body'] = df['txt_body'].apply(lambda x: x.lower())
df['txt_body'] = df['txt_body'].apply(remove_punctuation)
df['txt_body'] = df['txt_body'].fillna("").map(word_tokenize)
df['txt_body'] = df['txt_body'].apply(lambda x: [word for word in x if word not in stop_words])
# Here is the problem space
df['search_count'] = df['txt_body'].str.count('cat')
print(df.head())
预期输出:
txt_body search_count
0 [ab, likes, dogs] 1
1 [bc, likes, cats] 1
2 [de, likes, cats, dogs] 2
3 [fg, likes, cats, dogs, cows] 3
4 [hi, two, grey, cats, brown, cat, two, dogs] 3
【问题讨论】:
-
你想计算前缀吗?否则,您将不得不对令牌进行词形还原或做一些词干...
-
嗨!是的,只计算实际单词的一部分就可以了。 Lemmatizing 有点问题,因为我正在寻找一种也可以应用于非英语数据集的解决方案。但是词干应该不是问题......你有什么建议?
标签: python-3.x pandas nlp nltk