繁体   English   中英

如何用python的字符串替换csv中的数字

[英]How to replace number in csv with a string with python

我正在尝试修复CSV文件的第一行。 如果标题中的列名称以az以外的其他字符开头,则必须添加NUM。 下面的代码修复了第一行每一列中的特殊字符,但由于某种原因无法获得!az。

path = ('test.csv')

for fname in glob.glob(path):

    with open(fname, newline='') as f:
        reader = csv.reader(f)
        header = next(reader) 
        header = [column.replace ('-','_') for column in header]
        header = [column.replace ('[!a-z]','NUM') for column in header]

我究竟做错了什么。 请提供建议。 谢谢

我相信您会希望将“ column.replace”部分替换为以下内容:

re.sub(r'[!a-z]', 'NUM', column)

完整的文档参考位于此处以获取详细信息: https : //docs.python.org/2/library/re.html https://www.regular-expressions.info/python.html

既然您说过要 'NUM',则可以执行类似的操作(可能更有效,但这显示了基本思想)。

import string

column = '123'

if column[0] not in string.ascii_lowercase:
    column = 'NUM' + column

# column is now 'NUM123'

您可以这样做。

# csv file: 
# 2Hello, ?WORLD
# 1, 2

import csv
with open("test.csv", newline='') as f:
    reader = csv.reader(f)
    header = next(reader)
    print("Original header", header)
    header = [("NUM" + header[indx][1::]) for indx in range(len(header)) if not header[indx][0].isalpha()]
    print("Modified header", header)

输出:

Original header ['2HELLO', '?WORLD']
Modified header ['NUMHELLO', 'NUMWORLD']

上面的列表理解等效于以下for循环:

 for indx in range(len(header)):
        if not header[indx][0].isalpha():
            header[indx] = "NUM" + header[indx][1::]

如果只想替换数字,请使用以下命令:

if header[indx][0].isdigit():

如果根据许多相关的字符串函数进行更改,则可以根据需要进行修改。 https://docs.python.org/2/library/string.html

暂无
暂无

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

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