Python CSV判断数字'组成并替换它

时间:2014-04-19 14:02:26

标签: python csv

我有一个python脚本来运行PostgreSQL并将其输出存储在CSV文件中。脚本和文件看起来像,

import sys, os
os.chdir('C:\Users\Heinz\Desktop')
print os.getcwd()

#set up psycopg2 environment
import psycopg2

#driving_distance module
query = """
    select *
    from driving_distance ($$
        select
            gid as id,
            source::int4 as source,
            target::int4 as target,
            cost::double precision as cost,
            rcost::double precision as reverse_cost
        from network
        $$, %s, %s, %s, %s
    )
"""

#make connection between python and postgresql
conn = psycopg2.connect("dbname = 'TC_area' user = 'postgres' host = 'localhost' password = 'xxxx'")
cur = conn.cursor()

#count rows in the table
cur.execute("select count(*) from network")
result = cur.fetchone()
k = result[0] + 1                #number of points = number of segments + 1

#run loops
rs = []
i = 1
while i <= k:
    cur.execute(query, (i, 100000000000, False, True))
    rs.append(cur.fetchall())
    i = i + 1

#import csv module
import csv
import tempfile
import shutil

j = 0
h = 0
ars = []
element = list(rs)

#export data to every row
filename = 'distMatrix.csv'
with open(filename, 'wb') as f:
    writer = csv.writer(f, delimiter = ',')
    while j <= k - 1:
        while h <= k - 1:
            rp = element[j][h][2]
            ars.append(rp)
            h = h + 1
        else:
            h = 0
            writer.writerow(ars)
            ars = []
        j = j + 1

#concerning about flow-connection
with open(filename, 'rb') as f, tempfile.NamedTemporaryFile(mode='wb', delete=False) as g:
    writer = csv.writer(g, delimiter = ',')
    for row in csv.reader(f):
        row = [element if float(element) < 10**6 else 0 for element in row]
        writer.writerow(row)

shutil.move(g.name, filename)


conn.close()

enter image description here

CSV文件中的数字是PostgreSQL计算的路径,我知道它们都是由以下数字组成的,我们称它们为生成器

0,1,0.844,0.69,0.567,0.387,0.156,0.31,0.433,0.613

我想写一些可以判断这2个条件的代码,然后编辑这个CSV文件中的每个字段,

  1. 如果CSV文件中的数字与其中一个生成器相同,则它们与原始数字保持一致
  2. 如果CSV文件中的数字不是生成器之一,那么代码可以判断这个数字由哪个生成器组成,例如,2 = 1 + 1 ,然后更改添加乘法,对于最后一个示例,将此数字替换为1 * 1
  3. 我认为这些附加代码应该在脚本的这一部分中实现,

    #export data to every row
    filename = 'distMatrix.csv'
    with open(filename, 'wb') as f:
        writer = csv.writer(f, delimiter = ',')
        while j <= k - 1:
            while h <= k - 1:
                rp = element[j][h][2]
                ars.append(rp)
                h = h + 1
            else:
                h = 0
                writer.writerow(ars)
                ars = []
            j = j + 1
    

    但是如何完成这项任务?请给我一些建议和提示,谢谢。

    我在Windows 8.1 x64下使用python 2.7.4。

1 个答案:

答案 0 :(得分:0)

您要求的第二部分有点令人困惑。但听起来对我来说,你需要一个生成器函数来从列表中按需提供值,并测试数字是否在列表中...

list = [ 0, 1, 0.844, 0.69, 0.567, 0.387, 0.156, 0.31, 0.433, 0.613 ]

def gen():
    for i in range(len(list)):
        yield list[i]

g = gen()

def test_the_number(nbr):
    if nbr-int(nbr) in list:
        print("Number in list")
    else:
        print(next(g))

nbr = 5 # not in list
test_the_number(nbr)

nbr =777 # also not in the list
test_the_number(nbr)

nbr = 0.844  # In the list
test_the_number(nbr)