import jieba #分词工具 import pandas as pd import os import warnings import logging jieba.setLogLevel(logging.INFO) warnings.filterwarnings("ignore") datafile = os.path.dirname(os.path.realpath(__file__))+"/news.csv" stop_word_file = os.path.dirname(os.path.realpath(__file__))+"/stop_word.txt" news = pd.read_csv(datafile, sep='\t') #1.将所有停用词读到一个list中 #------------------Begin-----------------# with open(stop_word_file, encoding='utf-8') as f: stop_words = #------------------End-----------------# def preprocess(data): data['processedNews']=None #为data添加新列'processedNews’存储分词后的数据 for j in range(data.shape[0]): #2.对新闻内容(news content)进行分词 #------------------Begin-----------------# s2=data['news content'][j] words = #填充代码,将s2分词 #------------------End-----------------# strWords=[] for i in words: strWords.append(i) #3.对句子中每一个词:判断该词是否在停用词表中 # 若不在,则删除 # 将所有剩余词用空格连接成字符串,并将其保存在一个新列“processedNews”中 #------------------Begin-----------------# strWords2 = strWords.copy() for i in ( ): if i in ( ): strWords2.remove(i) linkwords = ' '.join( ) #------------------End-----------------# data['processedNews'][j]=linkwords preprocess(news) for processedNew in news['processedNews']: print(len(processedNew), end = ' ')
时间: 2025-05-31 10:53:13 浏览: 15
### 使用 Jieba 对 Pandas 数据框中的新闻内容进行分词并移除停用词
以下是实现该功能的完整代码示例:
```python
import pandas as pd
import jieba
# 假设有一个包含新闻内容的数据框 df,其中有一列名为 'content'
df = pd.DataFrame({'content': ['这是一条测试新闻的内容', '另一条新闻用于演示']})
# 加载停用词表
def load_stopwords(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
stopwords = set(line.strip() for line in file)
return stopwords
stopwords_file = "C:\\Python_DM\\2.4\\StopwordsCN.txt"
stopwords = load_stopwords(stopwords_file)
# 定义分词函数,并过滤掉停用词
def segment_text(text, stopwords):
words = jieba.lcut(text) # 使用精确模式进行分词
filtered_words = [word for word in words if word not in stopwords and word.strip()]
return " ".join(filtered_words)
# 应用分词和去停用词操作到 DataFrame 的每一行
df['segmented_content'] = df['content'].apply(lambda x: segment_text(x, stopwords))
print(df[['content', 'segmented_content']])
```
#### 说明
1. **加载停用词**
需要先定义 `load_stopwords` 函数来读取停用词文件[^1]。这里假设停用词存储在一个文本文件中,每行为一个停用词。
2. **分词与过滤**
利用 `jieba.lcut()` 方法对字符串进行分词[^1]。通过列表推导式筛选出不在停用词集合中的词语,并将结果拼接成新的字符串。
3. **应用到数据框**
将自定义的分词函数应用于整个数据框的指定列(这里是 `'content'`),并将结果存入新列 `'segmented_content'` 中。
---
### 注意事项
- 如果路径中有反斜杠 `\`,需将其转义为双反斜杠 `\\` 或者使用原始字符串前缀 `r`。
- 确保停用词文件编码正确,通常建议使用 UTF-8 编码[^2]。
---
阅读全文
相关推荐


















