python - sed 到 python 替换额外的分隔符
问题描述
sed 's/\t/_tab_/3g'
我有一个 sed 命令,它基本上替换了我的文本文档中所有多余的制表符分隔符。我的文档应该是 3 列,但偶尔会有一个额外的分隔符。我无法控制这些文件。
我使用上面的命令来清理文档。但是我对这些文件的所有其他操作都在 python 中。有没有办法在 python 中执行上述 sed 命令?
样本输入:
Column1 Column2 Column3
James 1,203.33 comment1
Mike -3,434.09 testing testing 123
Sarah 1,343,342.23 there here
样本输出:
Column1 Column2 Column3
James 1,203.33 comment1
Mike -3,434.09 testing_tab_testing_tab_123
Sarah 1,343,342.23 there_tab_here
解决方案
您可以逐行读取文件,使用制表符拆分,如果超过 3 个项目,则将第 3 个项目之后的项目用_tab_
:
lines = []
with open('inputfile.txt', 'r') as fr:
for line in fr:
split = line.split('\t')
if len(split) > 3:
tmp = split[:2] # Slice the first two items
tmp.append("_tab_".join(split[2:])) # Append the rest joined with _tab_
lines.append("\t".join(tmp)) # Use the updated line
else:
lines.append(line) # Else, put the line as is
该lines
变量将包含类似
Mike -3,434.09 testing_tab_testing_tab_123
Mike -3,434.09 testing_tab_256
No operation here
推荐阅读
- google-cloud-platform - Google Cloud AI Platform:图像数据标签服务错误 - 图像 URI 无效
- php - 如何返回其中包含 json 数组的 json 对象?
- build.gradle - gRPC 生成的 java 文件被重复或重新生成:类 ClassNameGrpc 是公共的,应在名为 ClassNameGrpc 的文件中声明
- django - django用户信息创建问题在admin中使用User.objects.create_user()
- python - 字段 'id' 需要一个数字,但得到了
- python - 如何将多个文件读取到数据框whiteout 中获取“已终止”错误消息?
- arrays - 避免在多维 JSON 对象中使用数组(和 [0])
- git - 如何将两个文件的 git 差异放入一个新文件中?
- amazon-web-services - AWS 服务角色与服务链接角色
- python - 如何在python中找到距离度量