一个字符在数据帧表单的文本中出现多少次

2024-04-20 08:14:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我是NLP中的乞丐,我有一个数据帧,其形式如下

text                         label 
----                        -----
This is he # first text     first label
This is the # second text   second label 
....                         ....

我想知道字符“#”在这个数据帧中读取了多少次。你能帮帮我吗?我正在寻找一个通用的代码,我可以计算“#”或其他字符或单词


2条回答

dt['text'].apply(lambda x: str.count(x, '#')).sum()

也许这不是最好的答案:

def count(text, target):
    words = text.split()
    counter = 0
    for word in words:
        if word == target:
            counter += 1
    return counter
df['counter'] = df.apply(lambda row: count(row['text'], target="#"),axis=1)
sum(df["counter"])

相关问题 更多 >