前言:请优先使用
string.replace
,其次考虑re
。
例如:我们有内容如下的 haha.csv表。现在我想把含有移动
的字段替换成另一个东西,比如你想换成yidong
好了。怎么做呢?
0 | time | … | weizhi |
---|---|---|---|
1 | 20180101 | … | 移动火车 |
2 | 20180101 | … | 移动飞机 |
3 | 20180101 | … | 移动椅子 |
4 | 20180101 | … | 海面木板 |
5 | 20180101 | … | 跟斗云 |
6 | 20180101 | … | 梦幻空间 |
7 | 20180101 | … | 黑洞 |
8 | 20180101 | … | 擂台 |
Excel: 首先,我们“ctrl + h”调出查找替换对话框;然后,设定要查找的为移动*
,要替换的为yidong
;最后,点击确认就好了。
Python: python的思路大致相同思路。
第一步,读取有n列的haha.csv表,再逐行处理;
第二步,使用正则表达式查找含有 移动
的记录;
第三步,设定要替换的为yidong
,再进行替换;
第四步,逐行逐行把替换好的记录添加到一块儿;
第五步,此时直接输出的csv仅为2列,需要调整格式,变为n列的csv文件。
第二版答案:
在第一版答案中,改进第二步、第三步和第四步,将代码由8行缩短为4行:
patterns = r'移动\w*'
regex = re.compile(patterns)
subplaced_data = regex.sub('yidong', line[i])
new_file.append(subplaced_data)
完整版:
import re
import pandas as pd
def tihuan(): # 设个函数,这样我们想运行它就调用它,不想就不调用。方便、主动。
# 第一步:
file = open('路径 + haha.csv', 'r')
lines = file.readlines()
new_file = []
for i in range(len(lines)):
# 第二步/第三步/第四步:
patterns = r'移动\w*'
regex = re.compile(pattern = patterns)
subplaced_data = regex.sub('yidong', lines[i]) # re.sub('查找的字符', '替换的字符', '指查找替换发生的地方')
new_file.append(subplaced_data)
# 第五步: # 没有这一步而直接.to_csv()的话,原表所有的列在新表里边全在一列。
new_file_csvformat = []
for i in new_file:
new_line_split = i.split(',')
new_file_csvformat.append(new_Line_split)
# 化为DataFrame格式,最后输出到指定位置
final_file = pd.DataFrame(new_file_csvformat)
final_file.to_csv('路径+新名字.csv', encoding='gbk', index=False, header=False)
# index=False不添加index列,Header=False不添加column行即我们使用原列名称
if __name__ == '__main__':
tihuan()
输出如下:
1 | time | … | weizhi |
---|---|---|---|
1 | 20180101 | … | yidong |
2 | 20180101 | … | yidong |
3 | 20180101 | … | yidong |
4 | 20180101 | … | 海面木板 |
5 | 20180101 | … | 跟斗云 |
6 | 20180101 | … | 梦幻空间 |
7 | 20180101 | … | 黑洞 |
8 | 20180101 | … | 擂台 |
第一版答案:
def tihuan(): # 设个函数,这样我们想运行它就调用它,不想就不调用。方便、主动。
# 第一步:
file = open('路径 + haha.csv', 'r')
lines = file.readlines()
new_file = []
for i in range(len(lines)):
# 第二步:
patterns = r'移动\w*'
regex = re.compile(pattern = patterns)
search_data = regex.search(lines[i])
# 第三步&第四步:
if search:
replaced_data = lines[i].replace(search_data.group(i), 'yidong') # .group()用于正则表达式中,返回位置i的内容。本处即所有含有“移动”的地方;
new_file.append(replaced_data)
else:
new_file.append(lines[i])
# 第五步:
new_file_csvformat = []
for i in new_file:
new_line_split = i.split(',')
new_file_csvformat.append(new_Line_split)
# 化为DataFrame格式,最后输出到指定位置
final_file = pd.DataFrame(new_file_csvformat)
final_file.to_csv(路径+新名字.csv', encoding='gbk')
if __name__ == '__main__':
tihuan()
注:
.group() :正则表达式中,group()用来提出分组截获的字符串,()用来分组,例如
import re
a = "123abc456"
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(0) #123abc456,返回整体
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(1) #123
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(2) #abc
print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(3) #456