【发布时间】:2014-11-23 07:33:02
【问题描述】:
我喜欢学习 Python,具有 C 语言背景。抱歉,如果我的问题是“幼稚”、“太简单”或“不够有效”。
在下面的代码中,我想练习未来的问题,通过“集合”数据结构删除特定行。但是,首先:它无法匹配删除集的内容。
另外,第二个问题:是o/p中的错误。这可以通过使缩进块工作来检查。
修剪后的数据文件为:marks_trim.csv
“Anaconda Systems 校园布局”,,,,,,,
“于:”,,,“2011 年 2 月 30 日”,,,
"Sno","Math","CS","GK","Prog","Comm","Sel"
1,"NA","NA","NA",4,0,0
import csv, sys, re, random, os, time, io, StringIO
datfile = sys.argv[1]
outfileName = sys.argv[2]
outfile = open(outfileName, "w")
count = 0
removal_list = set()
tmp = list()
i=0
re_pattern = "\d+"
with open(datfile, 'r') as fp:
reader1 = csv.reader(fp)
for row in reader1:
if re.match(re_pattern, row[0]):
for cols in row:
removal_list.add(tuple(cols)) #as tuple is hashable
print "::row>>>>>>",row
print "::removal_list>>>>>>>>",removal_list
convert = list(removal_list)
print "<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>"
print convert
f = open(datfile, 'r')
reader2 = csv.reader(f)
print ""
print "Removal List Starts"
print removal_list
print "Removal List Ends\n"
new_a_buf = io.BytesIO() # StringIO.StringIO() : both 'io' & StringIO' work
writer = csv.writer(new_a_buf)
rr =""
j = 0
for row in reader2:
if row not in convert: # removal_list: not used as list not hashable
writer.writerow(row) #outfile.write(new_a_buf)
'''
#below code using char array isn't used as it doesn't copy structure of csv file
for cols in row: #at indentation level of "if row not in convert", stated above
if cols not in convert: # removal_list: not used as list not hashable
for j in range(0,len(cols)):
rr+=cols[j] #at indentation level of "if cols not in convert:"
outfile.write(rr) # at the indentation level of 'if'
print "<<<<<<<<<<<<<<<<", rr
f = open(outfile, 'r')
reader2 = csv.reader(f)
'''
new_a_buf.seek(0)
reader2 = csv.reader(new_a_buf)
for row in reader2:
print row
问题/问题:
o/p 中的常见错误(即使用 char 数组 / csv.writer 对象)也给出了要删除的行,即在 removal_list 中出现。
但是,在使用 char 数组检索遗漏行的方法中,错误是:
Traceback(最近一次调用最后一次):
文件“test_list_in_set.py”,第 51 行,在
f = open(outfile, 'r')
TypeError:强制转换为 Unicode:需要字符串或缓冲区,找到文件
【问题讨论】:
-
试着让问题简短而简短..
-
里亚德所说的。请修复代码示例的格式/缩进。
标签: python