set(stopwords.words(‘english‘))

转载于:https://blog.csdn.net/miaoxiaowuseng/article/details/107343427

 

 

python处理停用词stopwords

 

停用词是什么

将数据转换为计算机可以理解的内容的过程称为预处理。预处理的主要形式之一是过滤掉无用的数据。在自然语言处理中,无用的单词(数据)称为停用词。
停用词是指搜索引擎已编程忽略的常用词(例如“the”,“a”,“an”,“in”)。
我们不希望这些单词占用我们数据库中的空间,或占用宝贵的处理时间。为此,我们可以通过存储要停止使用的单词的列表轻松删除它们。python中的NLTK(自然语言工具包)具有以16种不同语言存储的停用词列表。可以在nltk_data目录中找到它们。home / pratima / nltk_data / corpora / stopwords是目录地址(不要忘记更改你的主目录名称)

从一段文本中删除停用词

from nltk.corpus import stopwords 
from nltk.tokenize import word_tokenize 

example_sent = "This is a sample sentence, showing off the stop words filtration."

stop_words = set(stopwords.words('english')) 

word_tokens = word_tokenize(example_sent) 

filtered_sentence = [w for w in word_tokens if not w in stop_words] 

print(word_tokens) 
print(filtered_sentence) 

 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

输出为

['This', 'is', 'a', 'sample', 'sentence', ',', 'showing', 
'off', 'the', 'stop', 'words', 'filtration', '.']
['This', 'sample', 'sentence', ',', 'showing', 'stop',
'words', 'filtration', '.']
 
  • 1
  • 2
  • 3
  • 4
 
encoding=utf-8 import nltk import json from nltk.corpus import stopwords import re eg_stop_words = set(stopwords.words('english')) sp_stop_words = set(stopwords.words('spanish')) all_stop_words = eg_stop_words.union(sp_stop_words) input_file_name = r'建模.txt' output_file_name = r'train.txt' out_file = open(output_file_name, encoding='utf-8', mode='w') 打开输出文件 with open(output_file_name, encoding='utf-8', mode='w') as output_file: # 打开输入文件,对每一行进行处理 with open(input_file_name, encoding='utf-8') as f: for idx, line in enumerate(f): print("正在处理第{}行数据".format(idx)) if idx == 0: # 第一行是列名, 不要 print(line) continue line = line.strip() sps = line.split("\t") # 将行按制表符分隔为列表 report_no = sps[0] target = sps[2] smses = sps[-1] smses = smses.strip(""") # 去掉短信两端的引号 smses = smses.replace("""", """) # 把两个双引号转换成单引号 root = json.loads(smses) # 解析 json 格式的短信 msg = "" for item in root: # 遍历短信中的每一条信息 body = item["body"] # 获取信息的正文 msg += body + "\n" # 把正文追加到总的信息传递过来的msg中 text = re.sub(r'[^\w\s]', '', msg) # 使用正则表达式去掉标点符号 text = re.sub(r'http\S+', '', text) # 去掉链接 text = re.sub(r'\d+', '', text)#去除数字 text = text.lower() words = text.split() filtered_words = [word for word in words if word not in all_stop_words] text = ' '.join(filtered_words) print(report_no + '\t' + target) msg = target + '\u0001' + text + '\n' out_file.write(msg) out_file.close()帮我改成用 pandas 处理
07-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值