Застрял на записи переменной длины в Codio - PullRequest
0 голосов
/ 14 февраля 2020

Мои инструкции: Загрузите файл с разделителями канала 'P'. Он состоит из 3 полей в каждой строке: имя | фамилия | день рождения.

Поиск имени «F» и фамилии «L», заменяя день рождения на «B». Запишите файл обратно в том же формате с разделителями.

import sys
import re
P= sys.argv[1]
F= sys.argv[2]
L= sys.argv[3]
B= sys.argv[4]
roster = []


# Loads the file at filepath
# Returns a 2d array with the data
#
def load2dArrayFromFile(filepath):
  file1 = open(filepath, 'r')
  data = file1.read()
  file1.close()
  for x in range(0, len(roster)):
    roster.append(data)

# Searches the 2d array 'records' for firstname, lastname.
# Returns the index of the record or -1 if no record exists
#
def findIndex(records, firstname, lastname):
  for x in roster:
    if re.search(firstname, roster):
      if re.search(lastname, roster):
        name = roster[x]

# Sets the birthday of the record at the given index
# Returns: nothing
def setBirthday(records, index, newBirthday):
  for x in roster:
    if re.match(name, roster[x]):
      roster[x][2] = newBirthday


# Convert the 2d array back into a string
# Return the text of the 2d array
def makeTextFrom2dArray(records):
  (', ').join(str(roster))


# Load our records from the file into a 2d array
records= load2dArrayFromFile(P)

# Find out which index, if any, has the name we are hunting
indexWeAreHunting= findIndex(records, F, L)

# Set the birthday record to the one we were passed
setBirthday(records, indexWeAreHunting, B)

# Convert the records into a text string
output= makeTextFrom2dArray(records)

Я думаю, что я на правильном пути, но когда я запускаю код, я получаю обратно:

Adam|Smithers|10101960

вместе с остальной частью массива, вместо:

Adam|Smithers|00000000

Хотя я все равно должен вернуть оставшуюся часть массива.

1 Ответ

0 голосов
/ 28 марта 2020

Это работает

# Get the filepath from the command line
import sys
import re
P= sys.argv[1] 
F= sys.argv[2]
L= sys.argv[3]
B= sys.argv[4]

# ----------------------------------------------------------------
# 
# Our Helper functions:
# 
# ----------------------------------------------------------------

#
# Loads the file at filepath 
# Returns a 2d array with the data
# 
def load2dArrayFromFile(filepath):
  # Your code goes here:
  records= []
  with open(filepath, 'r') as f:
    element=f.readlines()
    for row in element:
      recordlist=row.strip('\n').split('|')
      records.append(recordlist)
  return records
#
# Searches the 2d array 'records' for firstname, lastname.
# Returns the index of the record or -1 if no record exists
# 
def findIndex(records, firstname, lastname):
  # Your code goes here:
  for x in range(len(records)):
    row = records[x]
    if row[0]== firstname and row[1]==lastname:
      return x
    
  return 
        
        
# Sets the birthday of the record at the given index
# Returns: nothing
def setBirthday(records, index, newBirthday):
  # Your code goes here:
  if index== None:
    return
  records[index][2]=newBirthday

# Convert the 2d array back into a string
# Return the text of the 2d array
def makeTextFrom2dArray(records):
  # Your code goes here:
  concat=[]
  charV=""
  for row in records:
    concat.append(("|").join(row))
  charV=("\n").join(concat)
  return charV
# ----------------------------------------------------------------
# 
#  Our main code body, where we call our functions.
#  
# ----------------------------------------------------------------

# Load our records from the file into a 2d array
records= load2dArrayFromFile(P)

# Find out which index, if any, has the name we are hunting
indexWeAreHunting= findIndex(records, F, L)

# Set the birthday record to the one we were passed
setBirthday(records, indexWeAreHunting, B)

# Convert the records into a text string
output= makeTextFrom2dArray(records)

# Your code goes here

# write the text string out to the file

outputFile = open(P,'w')
outputFile.write(output)
outputFile.close
...