Python拆分列中文和 字符

需求描述:我们日常实际的工作中经常需要把一列数据按中文和 数字或者字母单独拆分出来

导入所需的库:

复制代码
import pandas as pd

定义函数 extract_characters,该函数接受三个参数:file_path(Excel文件路径)、sheet_name(工作表名称)和 column_name(列名)。

复制代码
def extract_characters(file_path, sheet_name, column_name):

读取Excel文件并将其存储到DataFrame中:

复制代码
df = pd.read_excel(file_path, sheet_name=sheet_name)

创建两个新的列 '中文''其他字符',并将它们添加到DataFrame中:

复制代码
df['中文'] = ''
df['其他字符'] = ''

遍历DataFrame的每一行数据:

复制代码
for index, row in df.iterrows():

获取指定列的值,并将其转换为字符串:

复制代码
text = str(row[column_name])

初始化两个空字符串变量 chineseother,用于存储中文字符和其他字符:

复制代码
chinese = ''
other = ''

遍历每个字符:

复制代码
for char in text:

判断当前字符是否为中文字符(Unicode范围为\u4e00\u9fff):

复制代码
if '\u4e00' <= char <= '\u9fff':

如果是中文字符,则将其添加到 chinese 字符串中:

复制代码
chinese += char

如果不是中文字符,则将其添加到 other 字符串中:

复制代码
other += char

将中文字符集合添加到新的 '中文' 列中:

复制代码
df.at[index, '中文'] = chinese

将其他字符集合添加到新的 '其他字符' 列中:

复制代码
df.at[index, '其他字符'] = other

返回处理后的DataFrame对象:

复制代码
return df

定义测试示例的文件路径、工作表名称和列名:

复制代码
file_path = r'测试.xlsx'
sheet_name = 'Sheet1'
column_name = '店铺销售sku'

调用 extract_characters 函数,并将结果存储在 result_df 中:

复制代码
result_df = extract_characters(file_path, sheet_name, column_name)

将处理后的DataFrame保存为Excel文件:

复制代码
result_df.to_excel('result.xlsx', index=False)

完整代码:

相关推荐
FishCoderh25 分钟前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅28 分钟前
Python函数入门详解(定义+调用+参数)
python
曲幽2 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时5 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿7 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee1 天前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay1 天前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python