示例
C:\Users\each\Desktop\1.csv
name,text
handsome,* 666ji赚钱
each,#$ %^搞毛 6
想要把text列中除了中文的杂项剔除用于词云分析之类,想要得到的效果是
name,text
handsome,赚钱
each,搞毛
python代码实现如下,需要安装re库
win+R输入cmd
回车
输入
pip install re
回车
打开python,输入并运行
import pandas as pd
import re
# 读取CSV文件
df = pd.read_csv('C:\\Users\\each\\Desktop\\1.csv')
# 定义一个函数来去除非中文字符,只保留中文字符
def remove_non_chinese(text):
if isinstance(text, str):
return re.sub(r'[^\u4e00-\u9fa5]', '', text)
return text
# 只对第二列应用该函数(假设第二列的列名为 'text')
df['text'] = df['text'].apply(remove_non_chinese)
# 将处理后的数据保存回CSV文件
df.to_csv('C:\\Users\\each\\Desktop\\2.csv', index=False)
就会在C:\Users\each\Desktop位置生成一个名为2的csv文件