Python:使用变量作为CSV中的查找引用并返回值

时间:2012-09-14 10:47:39

标签: python csv lookup

找不到这个解决方案的答案,所以一旦我弄清楚了,我以为我会重新发布我的解决方案......

我一直在寻找一种获取用户输入(sys.argv[1])的方法,并使用此值在CSV文件中为列x中的另一个值(例如5)执行查找。这将是一个更大的脚本的一部分,我会使用查找值作为测试。

我的例子csv将是:

col0,col1,col2,col3,col4
a,foo,bar,blah,1
b,foo,bar,blah,2
c,foo,bar,blah,3
d,foo,bar,blah,4
e,foo,bar,blah,5
f,foo,bar,blah,6
g,foo,bar,blah,7
h,foo,bar,blah,8
i,foo,bar,blah,9
j,foo,bar,blah,10
k,foo,bar,blah,11
l,foo,bar,blah,12
m,foo,bar,blah,13
n,foo,bar,blah,14
o,foo,bar,blah,15
p,foo,bar,blah,16
q,foo,bar,blah,17
r,foo,bar,blah,18
s,foo,bar,blah,19
t,foo,bar,blah,20
u,foo,bar,blah,21
v,foo,bar,blah,22
w,foo,bar,blah,23
x,foo,bar,blah,24
y,foo,bar,blah,25
z,foo,bar,blah,26

2 个答案:

答案 0 :(得分:3)

我快速浏览了一下你的Javascript问题,如果你只是在字母表中映射char->位置,那么下面呢?

def char_to_pos(char):
    from string import ascii_lowercase
    try:
        return ascii_lowercase.index(char) + 1
    except ValueError as e:
        pass # no match - do what's sensible here

如果你想预先生成一个查找表,那么就像:

from string import ascii_lowercase
from itertools import count

lookup = dict(zip(ascii_lowercase, count(1)))
# or depending on taste
lookup = {letter: idx for idx, letter in enumerate(ascii_lowercase, start=1)}

否则,由于CSV文件通常相对较小,您可以将整个文件加载到RAM中以避免以后重复的顺序查找(只要CSV不那么大就会使您的机器处于昏迷状态)

with open('test1.csv') as fin:
    csvin = csv.reader(fin)
    lookup = {row[0]: row for row in csvin}

to_find = 'x'
try:
    print '{} = {[4]}'.format(to_find, lookup[to_find])
except (KeyError, IndexError) as e:
    pass # KeyError = no lookup match, IndexError is that CSV file didn't have 5th column...

答案 1 :(得分:1)

我这样做的方式如下:

import sys
import csv
#define user input as variable
input = sys.argv[1]
# read csv file into "fooReader"
fooReader = csv.reader(open('test1.csv', 'rb'), delimiter = ',', quotechar="\"")
# read each row in "fooReader"
for row in fooReader:
        # define first row column as "value" for testing
        value = row[0]
        # test if value (1st column) is the same as input (user input)
        if value == input:
                # ...if it is then print the 5th column in a certain way
                print value + " = " + row[4]

然后可以使用它将row[4]作为变量分配给另一个所需的测试。