gpt4 book ai didi

python - 删除停用词/标点符号,标记并应用 Counter()

转载 作者:行者123 更新时间:2023-12-04 09:28:28 30 4
gpt4 key购买 nike

我编写了一个函数来删除停用词和标记化,如下所示:

def process(text, tokenizer=TweetTokenizer(), stopwords=[]):    
text = text.lower()
tokens = tokenizer.tokenize(text)
return [tok for tok in tokens if tok not in stopwords and not tok.isdigit()]
我正在将它应用于专栏 tweet['cleaned_text']如下:
punct = list(string.punctuation)
stopword_list = stopwords.words('english') + punct + ['rt', 'via', '...','“', '”','’']

tf = Counter()
for i in list(tweet['cleaned_text']):
temp=process(i, tokenizer=TweetTokenizer(), stopwords=stopword_list)
tf.update(temp)
for tag, count in tf.most_common(20):
print("{}: {}".format(tag, count))
输出应该是最常用的词。这里有:
#blm: 12718
black: 2751
#blacklivesmatter: 2054
people: 1375
lives: 1255
matter: 1039
white: 914
like: 751
police: 676
get: 564
movement: 563
support: 534
one: 534
racist: 532
know: 520
us: 471
blm: 449
#antifa: 414
hate: 396
see: 382
如您所见,我无法删除标签 #尽管它包含在 punctuation 中列表(一些停用词也很明显)。 #blm 和 blm 在应该相同时被重复计算。
我一定在代码中遗漏了一些东西。

最佳答案

当您处理 token 时,您将保留整个单词,如果您想去掉前导 #您可以使用 str.strip("#")

def process(text, tokenizer=TweetTokenizer(), stopwords=[]):    
text = text.lower()
tokens = tokenizer.tokenize(text)
return [tok.strip("#") for tok in tokens if tok not in stopwords and not tok.isdigit()]

关于python - 删除停用词/标点符号,标记并应用 Counter(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62934652/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com