1

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

我正在寻找一种获取用户输入 ( 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
4

2 回答 2

3

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

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...
于 2012-09-14T11:15:02.900 回答
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]另一个所需测试中的变量。

于 2012-09-14T10:47:38.853 回答