简体   繁体   English

使用 re.sub python 删除一行中的所有字符

[英]Remove all characters in a row with re.sub python

I am trying to edit the data to replace ALL characters before a set point.我正在尝试编辑数据以替换设定点之前的所有字符。 Currently I have got this far with Python but this gives me a error "TypeError: 'str' object is not callable"目前我已经使用 Python 做到了这一点,但这给了我一个错误“TypeError: ‘str’ object is not callable”

Here is the data set before and what I am trying to achieve:这是之前的数据集以及我想要实现的目标:

Header 1,Header 2,Header 3,Header 4,Header 5 
1,2,3,4,DESCRIPTION
1,2,3,4,DEffffSCRIPTION
1,2,3,4,aaaaDESCRIPTION
1,2,3,4,<>DESCRIPTION

Here is what I am trying to achieve:这是我想要实现的目标:

Header 1,Header 2,Header 3,Header 4,Header 5 
1,2,3,4,SCRIPTION
1,2,3,4,SCRIPTION
1,2,3,4,SCRIPTION
1,2,3,4,SCRIPTION

If you can help fix the TypeError in the re.sub or if you can help overall that would be great thank you.如果您可以帮助修复 re.sub 中的 TypeError 或者您可以提供整体帮助,那将非常感谢。

Here is my python code.这是我的python代码。

import csv
import re

with open('2.csv', "r") as inFile:
    reader = csv.reader(inFile)
    for row in reader:
        row[4](re.sub(r'.*SC', r'SC.*', row[4]))

I think you just have a small syntax error on this line.我认为您在这一行只有一个小的语法错误。

row[4](re.sub(r'.*SC', r'SC.*', row[4]))

row[4] is a string, so you can't call re.sub on it like that. row[4] 是一个字符串,所以你不能像这样调用 re.sub 。 You need to store the output of re.sub in a variable.您需要将 re.sub 的输出存储在一个变量中。

subbed_row = re.sub(r'.*SC', r'SC.*', row[4])

And from there figure out how you want to write that back into the csv.从那里找出你想如何将它写回 csv。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM