删除 stopwords/punctuation、标记化并应用 Counter()
remove stopwords/punctuation, tokenize and apply Counter()
我编写了一个函数来删除停用词并标记如下:
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 在应该相同的时候被重复计算。
我一定是在代码中遗漏了一些东西。
当你处理标记时,你会保留整个单词,如果你想去掉前导 #
你可以使用 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()]
我编写了一个函数来删除停用词并标记如下:
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 在应该相同的时候被重复计算。
我一定是在代码中遗漏了一些东西。
当你处理标记时,你会保留整个单词,如果你想去掉前导 #
你可以使用 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()]