我有一个文件看起来像这个
a:1
a:2
a:3
b:1
b:2
b:2
我希望它取文件的a和b部分,并将其添加为第一列和下面的数字,如下所示。
a b
1 1
2 2
3 3
这能做到吗?
CSV(逗号分隔文件(中应该有逗号,因此输出应该有逗号而不是空格分隔符。
我建议将代码分为两部分:第一部分应该读取输入;第二个应该写出输出。
如果你的输入看起来像这样:
a:1
a:2
a:3
b:1
b:2
b:2
c:7
你可以阅读这样的输入:
#!/usr/bin/env python3
# Usage: python3 scripy.py < input.txt > output.csv
import sys
# Loop through all the input lines and put the values in
# a list according to their category:
categoryList = {} # key => category, value => list of values
for line in sys.stdin.readlines():
line = line.rstrip('n')
category, value = line.split(':')
if category not in categoryList:
categoryList[category] = []
categoryList[category].append(value)
# print(categoryList) # debug line
# Debug line prints: {'a': ['1', '2', '3'], 'b': ['1', '2', '2']}
这将把你的所有数据读入一个categoryList dict。这是一个包含类别(字母(作为键,包含列表(数字(作为值的dict。一旦你在dict中保存了所有数据,你就可以输出它
输出包括获得一个类别列表(在您的示例中是字母(,以便它们可以首先作为标题写出来:
# Get the list of categories:
categories = sorted(categoryList.keys())
assert categories, 'No categories found!' # sanity check
从这里,您可以使用Python的nicecsv模块来输出标题,然后输出其余的行。当输出主数据时,我们可以使用外循环来循环通过每个类别的nth条目,然后我们可以使用内循环来循环每个类别:
import csv
csvWriter = csv.writer(sys.stdout)
# Output the categories as the CSV header:
csvWriter.writerow(categories)
# Now output the values we just gathered as
# Comma Separated Values:
i = 0 # the index into an individual category list
while True:
values = []
for category in categories:
try:
values.append(categoryList[category][i])
except IndexError:
values.append('') # no value, so use an empty string
if len(''.join(values)) == 0:
break # we've run out of categories that contain input
csvWriter.writerow(values)
i += 1 # increment index for the next time through the loop
如果你不想使用Python的csv模块,你仍然需要弄清楚如何将类别中的条目分组在一起。如果您所拥有的只是简单的输出(其中没有一个条目包含引号、换行符或逗号(,那么您可以手动写出输出。
你可以使用这样的东西来输出你的值:
# Output the categories as the CSV header:
print(','.join(categories))
# Now output the values we just gathered as
# Comma Separated Values:
i = 0 # the index into an individual category list
while True:
values = []
for category in categories:
try:
values.append(categoryList[category][i])
except IndexError:
values.append('') # no value, so use an empty string
if len(''.join(values)) == 0:
break # we've run out of categories that contain input
print(','.join(values))
i += 1 # increment index for the next time through the loop
这将打印出来:
a,b,c
1,1,7
2,2,
3,2,
它通过循环所有列表条目(外部循环(,然后循环所有类别(内部循环(,再打印出用逗号连接在一起的值来实现这一点。
如果您不希望在输出中使用逗号,那么从技术上讲,您不是在寻找CSV(逗号分隔值(输出。不过,在这种情况下,修改代码以获得所需内容应该很容易。
但是,如果您有更复杂的输出(即,包含引号、逗号和换行符的值(,则应强烈考虑使用csv模块来输出数据。否则,您将花费大量时间尝试修复csv模块已经处理的带有奇怪输入的模糊错误。