0

输入文本:

May 2014, 156
May 2013, 556
May 2013, 651

我将此数据添加到input.csv文件中:

import csv

with open("text_file.txt") as inputFile:
    for line in inputFile:
        vars = [line.strip().split(",") for line in inputFile]
        print vars
        #set True if you want to export input as csv file
        convert_to_csv = True
        if convert_to_csv == True:
            with open('input.csv', 'w') as fp:
                a = csv.writer(fp, delimiter=',')
                data = [['Text', 'Count']] + vars
                a.writerows(data)

如何从我的变量中获取变量vars并将 10(例如:156 + 10)添加到我的“计数”值?

打印变量输出:

[['May 2013', 156], ['May 2013', 556]]

计算后计数 = 计数 + 10,我也想将输出写入带有标题的 csv 文件(output.csv)['Text', 'Count after calc']

4

2 回答 2

0

您需要将字符串解析为整数,然后将其加 10。

vars = [line.strip().split(",") for line in inputFile]
vars = [[v[0],int(v[1])+10] for v in vars]
#             ^^^^^^^^^^^^
print vars

请注意,这不是一个完整的代码,您将不得不执行更多检查,例如如果第二项不是整数怎么办?拆分时,,如果项目数不等于 2 怎么办?

于 2013-11-14T08:43:53.233 回答
0

稍微重构一下:

#!/usr/bin/python
import csv

with open('text_file.txt') as input_file:
    csv_data = []

    for row in csv.reader(input_file, delimiter=','):
        csv_data += [[row[0], int(row[1].strip()) + 10]]

    convert_to_csv = True

    if convert_to_csv:
        with open('input.csv', 'w') as output_file:
            csv_file = csv.writer(output_file, delimiter=',')
            csv_file.writerow(['Text', 'Count'])

            for row in csv_data:
                csv_file.writerow(row)

对于您所描述的,它运行良好。祝你好运!:)

于 2013-11-14T08:54:47.683 回答