读取CSV d时删除特定字符串

2024-04-27 03:16:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我正在编写一个从CSV文件读取数据的代码。你知道吗

数据如下所示:

10944750,13451,0,6��4��   

10944750,21110,0,6��7��

10944750,1131,0,7��23��

10944750,8689,0,5��2��

最后一列表示日期,例如第一行中的日期:June 4th。但里面有两个中国宪章。所以我得把它解码,得到月份和日期。你知道吗

我的代码:

import codecs
raw_file=open('Documents/t_alibaba_data.csv')
result=open('Documents/result.txt','w')
for line in raw_file.readlines():
    entry=line.split(",")
    deco=entry[3].decode("gbk")
    month=deco[0]
    if len(deco)==5:
        day=int(deco[2])*10+int(deco[3])
    else:
        day=int(deco[2])
    result.write(",".join(entry[:3])+","+str(month)+","+str(day)+"\n")
        print result

IDE中没有警报或错误,但结果中也没有任何内容。你知道吗


Tags: csv代码rawlineresultopendocumentsfile
1条回答
网友
1楼 · 发布于 2024-04-27 03:16:04

首先:您没有告诉Python您想从文件中读取。(将“r”添加到原始_文件.open(). 你知道吗

并且,在运行程序时,在解码最后一列之后,元素nr3(deco[2])是一个中文符号,而不是一天的nr。你知道吗

我稍微调整了一下你的程序,当它看起来像这样时,它就起作用了(至少如果我正确理解了你的问题):

import codecs
raw_file=open('Documents/t_alibaba_data.csv', 'r')
result=open('Documents/result.txt','w')
for line in raw_file.readlines():
    entry=line.split(",")
    deco=entry[3].decode("gbk").strip()
    month=deco[0]
    if len(deco)==5:
        day=int(deco[2])*10+int(deco[3])
    else:
        day=int(deco[4])
    result.write(",".join(entry[:3])+","+str(month)+","+str(day)+"\n")
result.close()

而且,len(deco)永远不会是5,if测试也永远不会是真的。长度总是大于5。试着打印出不同装饰的长度,看看实际长度是多少。 明智的做法是在deco上使用strip函数,以防字符串末尾有空格。当我打印您作为示例给出的装饰的长度时,长度是8或9,这取决于正在处理的线条。你知道吗

相关问题 更多 >