我的停用词保存在了一个txt文件中,可以帮我再重新改一下代码嘛
时间: 2024-03-14 19:45:34 浏览: 12
当然可以,将停用词保存在 txt 文件中也很常见。下面是对上面代码的修改,使其可以读取 txt 文件中的停用词:
```python
import re
import jieba
import pandas as pd
# 读取微博数据
df = pd.read_csv('weibo.csv')
# 读取停用词文件
stopwords = []
with open('stopwords.txt', encoding='utf-8') as f:
for line in f:
stopwords.append(line.strip())
# 去除 HTML 标签和表情符号
def clean_text(text):
# 去除 HTML 标签
text = re.sub('<[^>]+>', '', text)
# 去除表情符号
text = re.sub('\[.*?\]', '', text)
return text
# 去除网址和@用户
def remove_url_and_at(text):
# 去除网址
text = re.sub('https?://[^\s]+', '', text)
# 去除@用户
text = re.sub('@[^\s]+', '', text)
return text
# 分词,去除停用词和标点符号
def tokenize(text):
# 分词
words = jieba.cut(text)
# 去除停用词和标点符号
words = [word.strip() for word in words if word.strip() not in stopwords and re.match(r'^[\w\u4e00-\u9fa5]+$', word)]
return words
# 对每条微博进行处理
for i, row in df.iterrows():
text = row['text']
# 去除 HTML 标签和表情符号
text = clean_text(text)
# 去除网址和@用户
text = remove_url_and_at(text)
# 分词,去除停用词和标点符号
words = tokenize(text)
# 将处理后的文本保存到新列中
df.at[i, 'processed_text'] = ' '.join(words)
# 将处理后的数据保存到新的 csv 文件中
df.to_csv('weibo_processed.csv', index=False, encoding='utf-8-sig')
```
上面的代码中,我们首先读取了停用词文件 `stopwords.txt`,并将其保存到列表 `stopwords` 中。在函数 `tokenize` 中,我们使用了这个列表来判断一个单词是否为停用词。代码中还包括了其他部分,与之前的示例代码基本相同。