我在使用csvreader创建字典密钥时遇到问题。我想创建一个字典,其中包含找到数据的位置列,以便以后可以将其写到新位置。我没有包括write函数,因为我想先了解如何创建键。
例如,该数据点123-123-1234位于第[0]行。
input_file_column_modification = ''
myData = []
primary_key_list = {}
if os.path.isfile(filename):
input_file_column_modification = open(filename)
myData = [item for item in csv.reader(input_file_column_modification)]
for row in myData:
primary_key_pattern_match = re.search('\d{3}-\d{3}-\d{4}, row[0], re.I)
if primary_key_pattern_match is not None:
** QUESTION: How do I keep track of the row/columns were the data is being found?
primary_key_list.append(primary_key_pattern_match.group(0))
正在读取的当前输入注意,2个条目没有要匹配的模式。
信息、地址、城市、ZipCode、上次更新
Lorem ipsum dolor sit amet,Concetetur(123-123-1234)Adipising elita,100 some address,cityname,“zipcode”,2016年3月24日
lorem ipsum dolor sit amet, consecetur adipiscing elit,200一些地址,城市名称,邮政编码,03/24/2016
Lorem ipsum dolor sit amet, consecetur(345-345-3456)adipiscing elit,300一些地址,城市名称,邮政编码,03/24/2016
Lorem ipsum dolor sit amet,Concetetur Adipising elit,400 some address,cityname,zipcode,2016年3月24日
Lorem ipsum dolor sit amet,Concetetur(567-567-5678)Adipising Elite,500 some address,cityname,zipcode,2016年3月24日
一种方法是通过enumerate
,它在循环时为您提供索引或“迭代计数器”以及可迭代的值:
for row_num, row in enumerate(myData):
primary_key_pattern_match = re.search('\d{3}-\d{3}-\d{4}, row[0]', re.I)
if primary_key_pattern_match is not None:
row_num_and_row_data = (row_num, row)
# You now have a tuple whose 1st element is the row number
# and whose 2nd element is the row (a tuple or list).
# You can also skip making a tuple and add the row
# to a dictionary immediately (declare it before the loop):
row_dict[row_num] = row
# or to add the results of the regex:
row_dict[row_num] = primary_key_pattern_match.group(0)