如何在CSV解析器python中获取具有值的列

2024-05-16 20:40:48 发布

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

CSV解析器中的另一个问题。 我需要将年份及其对应的国家填充到sqlite数据库中的表中。我已经成功地缩小了范围,以获得所有行的值(如果其中任何一行有值的话)。但是试图将()数据保存到数据库中,对于没有任何值的数据,它抛出ValueError: invalid literal for int() with base 10: ''。你知道吗

if (row[12] or row[13] or row[14] or row[15] ) != "":
                    country1 = re.match(r'.*\((\w+)\)', header[12])
                    country2 = re.match(r'.*\((\w+)\)', header[13])
                    country3 = re.match(r'.*\((\w+)\)', header[14])
                    country4 = re.match(r'.*\((\w+)\)', header[15])
                    Yr.country = country1 
                    Yr.country = country2 
                    Yr.country = country3 
                    Yr.country = country4 
                    Yr.mol = MoleculeDictionary.objects.get(id=row[0])
                    Yr.year = row[12]
                    Yr.year = row[13]
                    Yr.year = row[14]
                    Yr.year = row[15]
                    #Yr.save()
                    print country1.group(1), row[12], country2.group(1), row[13], country3.group(1), row[14], country4.group(1), row[15]




Year (US),Year (Eur),Year (Jap), Yea(CHI),
    ,,,,,
    ,,,,,
    ,,,,,
    ,,2009,,,
    ,,1977,,,
    ,1982,1983,,,

打印报表打印

US  Eur 2009 Jap  CHI 
US  Eur 1977 Jap  CHI 
US 1982 Eur 1983 Jap  CHI 

但我更希望只得到每个列中都有值的列划船。怎么划船我应该只得到欧元2009年,欧元1977年,美国1982年,欧元1983年。请忽略我的无能,因为我对python和Django。谢谢所有的建议。你知道吗

谢谢。你知道吗


Tags: orrematchgroupeuryearcountryrow
1条回答
网友
1楼 · 发布于 2024-05-16 20:40:48

我不明白你的意思

would rather like to get only the columns with values in each row

所以也许你可以指定你想要的输出?你知道吗

但是,如果您的csv是test.csv,那么这个脚本

import csv

with open('test.csv') as myfile:
    reader = csv.reader(myfile)
    header = []
    for row in reader:
        if header == []: # first row
            header = row
        else:
            for i in range(len(row)):
                if row[i] != '':
                    # calculate custom header
                    custom_header = header[i].split('(')[1].split(')')[0].upper()
                    print custom_header, row[i]

将打印

JAP 2009
JAP 1977
EUR 1982
JAP 1983

这就是你想要的吗?你知道吗

相关问题 更多 >