【问题标题】:What is a clean way to replace the column values in a CSV file?替换 CSV 文件中的列值的干净方法是什么?
【发布时间】:2021-05-26 17:07:37
【问题描述】:

我有一个 CSV 文件,其中有一列名为“电池寿命”。数据可以是数字或附加到它的字符串。 “hr”或“hrs”是那些字符串(表示电池使用时间)。少数样本是 3hr、3hr、3hrs、3hrs 等。有一种情况是数据不可用,列值为“不可用”

这是我试图处理的数据示例。请参阅名为 Battery_life 的最后一列。 dropbox.com/s/z75wleoy3153c8o/headphonesV1-csv.csv?dl=0

我正在尝试从 CSV 列中删除 hr 和 hrs 部分。

这是我迄今为止所做的,它有效,但不是一个好的解决方案,即使我几个月前才开始编码,我也不为此感到自豪。

data = open("headphonesV1 copy.csv", "r")

# join() method combines all contents of
# csvfile.csv and formed as a string
data = ''.join([i for i in data])

# search and replace the contents
data = data.replace("hrs", "")
data = data.replace("hr", "")


# output.csv is the output file opened in write mode
x = open("headphonesV1 copy.csv", "w")

# all the replaced text is written in the output.csv file
x.writelines(data)
x.close()

我尝试的另一种方法是定义如下函数并从列中进行字符串替换。

def clean_battery_string(input_string):

    if "hrs" in input_string:

        clean_string = input_string.replace("hrs", '')
        print(clean_string)
    elif "hr" in input_string:
        clean_string = input_string.replace("hr", '')
        print(clean_string)
    else:
        clean_string = input_string
        print(clean_string)

    return clean_string

但我不确定如何应用此功能。有人可以帮忙吗

【问题讨论】:

    标签: python python-3.x string csv replace


    【解决方案1】:

    您的第二个变体将不起作用,因为如果您有字符串 hrs 和 hr,则只会替换 hrs。

    第一个变种还不错,但我想优化你的代码。

    data = open("headphonesV1 copy.csv", "r")
    
    # join() method combines all contents of
    # csvfile.csv and formed as a string
    data = data.read()
    
    # search and replace the contents
    data = data.replace("hrs", "")
    data = data.replace("hr", "")
    
    
    # output.csv is the output file opened in write mode
    x = open("headphonesV1 copy.csv", "w")
    
    # all the replaced text is written in the output.csv file
    x.write(data)
    x.close()
    

    首先,如果你想输出文件有多行,比如输入,我使用data.read()(返回一个str\n 符号)而不是''.join([i for i in data])

    【讨论】:

    • 对不起我的英语不好
    • 谢谢。但是如果 hr 或 hrs 在任何其他列中,这段代码也会替换它们吗?这就是我的代码的问题。
    • @TonyPaul CSV 是一个包含数据的文本文件,以逗号分隔。此代码将替换文档中的所有hrshr。也许我不明白你的文件示例?你能复制/粘贴你的文件到pastebin吗?
    • 我还没用过粘贴箱。这是文件的示例 - dropbox.com/s/z75wleoy3153c8o/headphonesV1-csv.csv?dl=0 。查看最后一列名称电池寿命。
    • @TonyPaul,是的,它适用于您的桌子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多