[英]Python - read txt file into list - display contents of the new list
我之前確實在另一個帳戶上問過這個問題,但我丟失了帳戶並且沒有看到人們給出的大多數評論或答案,所以我在我的這個舊帳戶上問過
我是 python 和一般編程的新手,所以我不明白我應該做什么才能獲得預期的 output。 我想我的 read_file function 是正確的,但我不確定。
我已經研究了一段時間,但我還沒有完全理解如何完成這部分。
此處的目標是以特定方式顯示文本文件中的配置文件。
規則是:
Your solutions MAY make use of the following:
• Built-in functions int(), input(), print(), range(), open(), close(), len() and str().
• Concatenation (+) operator to create/build new strings.
• The list_name.append(item) method to update/create lists.
• Access the individual elements in a string with an index (one element only). i.e. string_name[index].
• Access the individual elements in a list with an index (one element only). i.e. list_name[index].
• Profile objects and methods (as appropriate).
• The list_function.py module (that you wrote in part A of this assignment). You may like to make use of some of the functions defined in the list_function.py module for this part of the assignment (as appropriate). Not all will be suitable or appropriate.
Your solutions MUST NOT use:
• Built-in functions (other than the int(), input(), print(), range(), open(), close() len() and str() functions).
• Slice expressions to select a range of elements from a string or list. i.e. name[start:end].
• String or list methods (i.e. other than those mentioned in the 'MAY make use' of section above.
• Global variables as described in week 8 lecture.
• The use break, return or continue statements (or any other technique to break out of loops) in your solution – doing so will result in a significant mark deduction.
以下是我得到的一些描述:
o display_summary(profile_list)
This function will take the list of profile objects as a parameter and will output the contents of the list to the screen. This function displays the information to the screen in the format specified in the assignment specifications under the section - 'Screen Format'. You must use a loop in your solution.
o read_file(filename, profile_list)
This function takes a file name and reads the contents of that file into the profile_list (list) passed as a parameter into the function. The function returns the list of profile objects. You must use a loop in your solution. You may use String and/or List methods in this function only. You may find the String methods split() and strip() useful here.
預期的 output 是:
Please enter choice [summary|add|remove|search|update|quit]: summary
==============================================================================
Profile Summary
==============================================================================
------------------------------------------------------------------------------
Fox Mulder (m | fox@findthetruth.com)
- The truth is out there!
- Friends (1):
Tony Stark
------------------------------------------------------------------------------
Tony Stark (m | tony@ironman.com)
- Saving the world is hard work - no time for friends.
- No friends yet...
------------------------------------------------------------------------------
Phil Dunphy (m | phil@dunphy.com)
- wtf? = why the face?
- Friends (2):
Robbie Gray
Fox Mulder
------------------------------------------------------------------------------
John Mayer (m | john@guitar.com)
- Waiting on the world to change!
- Friends (2):
Katy Perry
David Guetta
------------------------------------------------------------------------------
Katy Perry (f | katy@perry.com)
- Waiting on John to change.
- Friends (3):
John Mayer
David Guetta
Jimmy Fallon
------------------------------------------------------------------------------
David Guetta (m | dguetta@willworkwithanyone.org)
- Will collaborate with anyone who has a heartbeat.
- Friends (5):
Katy Perry
John Mayer
Tony Stark
Fox Mulder
Robbie Gray
------------------------------------------------------------------------------
Jimmy Fallon (m | jimmy@tonightshow.com)
- I wish I was as good as Letterman, thank goodness he's retiring.
- Friends (2):
Robbie Gray
Tony Stark
------------------------------------------------------------------------------
Robbie Gray (m | robbie@football.com)
- Training hard... can we win? Yes we Ken!
- Friends (4):
Jimmy Fallon
Fox Mulder
John Mayer
Tony Stark
------------------------------------------------------------------------------
==============================================================================
正在從如下所示的文本文件中讀取文本:
Fox Mulder fox@findthetruth.com m
The truth is out there!
1
tony@ironman.com
Tony Stark tony@ironman.com m
Saving the world is hard work - no time for friends.
0
Phil Dunphy phil@dunphy.com m
wtf? = why the face?
2
robbie@football.com
fox@findthetruth.com
John Mayer john@guitar.com m
Waiting on the world to change!
2
katy@perry.com
dguetta@willworkwithanyone.org
Katy Perry katy@perry.com f
Waiting on John to change.
3
john@guitar.com
dguetta@willworkwithanyone.org
jimmy@tonightshow.com
David Guetta dguetta@willworkwithanyone.org m
Will collaborate with anyone who has a heartbeat.
5
katy@perry.com
john@guitar.com
tony@ironman.com
fox@findthetruth.com
robbie@football.com
Jimmy Fallon jimmy@tonightshow.com m
I wish I was as good as Letterman, thank goodness he's retiring.
2
robbie@football.com
tony@ironman.com
Robbie Gray robbie@football.com m
Training hard... can we win? Yes we Ken!
4
jimmy@tonightshow.com
fox@findthetruth.com
john@guitar.com
tony@ironman.com
到目前為止,我已經做到了:
import profile
def get_menu_choice():
list_choice = ['summary', 'add', 'remove', 'search', 'update', 'quit']
#User inputs an option
choice = input(str('\nPlease enter choice [summary|add|remove|search|update|quit]: '))
#Start a loop if they enter an invalid input
while choice not in list_choice:
print('\nNot a valid command - please try again.')
choice = input(str('\nPlease enter choice [summary|add|remove|search|update|quit]: '))
#end of loop here
return choice
# Function read_file() - place your own comments here... : )
def read_file(filename, profile_list):
profile_list = []
filename = open("profiles.txt", "r")
for line in filename:
stripped_line = line.strip()
profile_list = stripped_line.split()
filename.append(profile_list)
filename.close()
print(profile_list)
# Function display_summary() - place your own comments here... : )
def display_summary(profile_list):
print('========================================')
print('Profile Summary')
print('========================================')
display_details()
active = 'y'
while active == 'y':
choice = get_menu_choice()
if choice == 'summary':
display_summary()
elif choice == 'quit':
active = 'n'
導入配置文件引用此文件:
class Profile:
# The __init__ method initializes the data attributes of the Profile class
def __init__(self, given_name='', family_name='', email='', gender='', status=''):
self.__given_name = given_name
self.__family_name = family_name
self.__email = email
self.__gender = gender
self.__status = status
self.__number_friends = 0
self.__friends_list = []
def set_given_name(self, name):
self.__given_name = name
def get_given_name(self):
return self.__given_name
def set_family_name(self, name):
self.__family_name = name
def get_family_name(self):
return self.__family_name
def set_email(self, email):
self.__email = email
def get_email(self):
return self.__email
def set_gender(self, gender):
self.__gender = gender
def get_gender(self):
return self.__gender
def set_status(self, status):
self.__status = status
def get_status(self):
return self.__status
def set_number_friends(self, no_friends):
self.__number_friends = no_friends
def get_number_friends(self):
return self.__number_friends
def set_friends_list(self, friends_list):
self.set_number_friends(len(friends_list))
self.__friends_list = friends_list
def get_friends_list(self):
return self.__friends_list
# The __str__ method returns a string representation of the object
def __str__(self):
string = self.__given_name + ' ' + self.__family_name + ' ' + self.__email + ' ' + self.__gender + '\n'
string += self.__status + '\n'
string += str(self.__number_friends) + '\n'
for friend_email in self.get_friends_list():
string += friend_email + '\n'
return string
# The method add_friend adds an email address to the friends_list only if the email doesn't already exist.
# No duplicate entries allowed. The method returns True if successful and False otherwise.
def add_friend(self, email):
# Check to see whether email already exists in the friends list
if self.is_friend(email) == True:
return False;
# Otherwise, okay to add friend and increment number of friends count
self.__friends_list.append(email)
self.__number_friends += 1
return True
# The method remove_friend removes an email address from the friends_list (if found).
# Method returns True if successful and False otherwise.
def remove_friend(self, email):
# Check to see whether email exists in the friends list
if self.is_friend(email) == False:
return False;
# Otherwise, okay to remove friend and decrement number of friends count
self.__friends_list.remove(email)
self.__number_friends -= 1
return True
# The method is_friend determines whether the email passed in as a parameter
# exists in the friends_list, i.e. they are friends.
# If the email is found in the friends_list, the method will return True.
# If the email is not found, the function returns False.
def is_friend(self, email):
found = False
for email_address in self.__friends_list:
if email == email_address:
found = True
return found
# The __eq__ method allows for a test for equality (is equal to) on email address i.e. == operator.
def __eq__(self, email):
if self.__email == email:
return True
elif self.__email != email:
return False
return NotImplemented
我對此感到很困惑。 任何人都能夠解釋它或提供任何指示。
我試圖讓這個問題盡可能容易理解。
謝謝。
Output 和之前一樣。 根據原始要求將代碼打包成兩個函數。
請查看此內容並了解如何在您的代碼中實現它。
# Function read_file()
def read_file(filename, profile_list):
profile_list = []
people = {}
temp = []
f1 = open(filename, "r")
for line in f1:
stripped_line = line.strip()
temp = stripped_line.split()
#check if line has name, email, and sex (profile info)
if (temp[-1] == 'm') or (temp[-1] == 'f'):
ln = len(temp)
temp_concat = ''
for i in range(ln-3):
temp_concat = temp_concat + temp[i] + ' '
temp_concat = temp_concat + temp[ln-3]
#store name, email, and sex as separate values into the list
profile_list.append([temp_concat, temp[-2], temp[-1]])
#store into dict: email as key, name as value for ease of lookup
people[temp[-2]] = temp_concat
else:
profile_list.append(stripped_line)
f1.close()
#add people dictionary as last item into the profile_list list
profile_list.append(people)
return profile_list
# Function display_summary()
def display_summary(profile_list):
#now we are ready to print the profiles
print ('=' * 78)
print ('Profile Summary')
print ('=' * 78)
#print_line will determine what kind of data to print
#profile: name (sex | email id) will be printed
#desc: description from second line will be printed
#friends: will print the Friends(#) where # is number of friends
#if no friends, No friends yet... will be printed
#if there are friends, friend_count will be set to # of friends
#friend_list: will print the friends. email id will be looked up for print
#for every friend printed from friend_list, the counter will be reduced
#when the last friend is printed, we will set the print_line back to 'profile'
print_line = 'profile'
friend_count = 0
people = profile_list[-1]
ln = len(profile_list)
c = 1
for data in profile_list:
if c != ln:
c += 1
if print_line == 'profile':
print ('-' * 78)
print (f'{data[0]} ({data[2]} | {data[1]})')
print_line = 'desc'
elif print_line == 'desc':
print (f'- {data}')
print_line = 'friends'
elif print_line == 'friends':
if data == '0':
print ('- No friends yet...')
print_line = 'profile'
else:
print (f'- Friends ({data})')
friend_count = int(data)
print_line = 'friend_list'
elif print_line == 'friend_list':
if data in people:
print(f' {people[data]}')
else:
print(f' {data}')
if friend_count == 1:
print_line = 'profile'
else:
friend_count -= 1
print ('-' * 78)
print ('=' * 78)
profile_list = []
profile_list = read_file("abc.txt", profile_list)
display_summary(profile_list)
問:這個 function 采用文件名並將該文件的內容讀入作為參數傳遞到 function 的 profile_list(列表)中。 function 返回配置文件對象列表。 您必須在解決方案中使用循環。 您只能在此 function 中使用字符串和/或列表方法。 您可能會發現這里的字符串方法 split() 和 strip() 很有用。
讓我們回顧一下您的 read_file() function。 下面是你的代碼。
# Function read_file() - place your own comments here... : )
def read_file(filename, profile_list):
profile_list = []
filename = open("profiles.txt", "r")
for line in filename:
stripped_line = line.strip()
profile_list = stripped_line.split()
filename.append(profile_list)
filename.close()
print(profile_list)
審核意見:
profile_list = []
- 很好地重置列表。filename = open ("profiles.txt", "r")
-> 您需要使用 function 參數中傳遞的文件名。 您應該將其重寫為f1 = open(filename, 'r')
for line in f1:
stripped_line = line.strip()
-> 好profile_list = stripped_line.split()
-> 你為什么不利用分割每一行的優勢? 您也不能將其存儲到profile_list
中。 這是您需要存儲所有行的最終列表。if (temp[-1] == 'm') or (temp[-1] == 'f')
。 如果是這樣,則該行具有配置文件名稱、email id 和配置文件性別。 更新了代碼並修復了read_file(filename, profile_list)
function
# Function read_file() - place your own comments here... : )
def read_file(filename, profile_list):
profile_list = []
temp = []
f1 = open(filename, "r")
for line in f1:
stripped_line = line.strip()
temp = stripped_line.split()
if (temp[-1] == 'm') or (temp[-1] == 'f'):
ln = len(temp)
temp_concat = ''
for i in range(ln-3): #process the first few and ignore last 3 values
temp_concat = temp_concat + temp[i] + ' '
temp_concat = temp_concat + temp[ln-3] #concat 3rd from last value as its part of the name
profile_list.append([temp_concat, temp[-2], temp[-1]]) #store as separate items within a list. it will help you retrieve them quickly
else:
profile_list.append(stripped_line)
f1.close()
print(profile_list)
return profile_list
profile_list = []
profile_list = read_file("profiles.txt", profile_list)
這是將打印配置文件摘要的代碼。 查看此代碼並將其與您的代碼進行比較。
明天,我將審查您的代碼並為您提供改進代碼的建議。 如果您可以查看以下代碼並了解我是如何完成的,它可能會幫助您理解處理邏輯。
#step 1: create an empty list to hold the contents of the file
file_data = []
people = {}
#step 2: read the file into a list
with open('profiles.txt','r') as f1:
for line in f1:
#file_data.append(line.strip('\n'))
#if strip('\n') is not allowed, then use below code
ln = len(line)
line_concat = ''
space_pos = []
#if line is just a number, add to list
if ln == 2:
file_data.append(line[0])
#if line is name + email + sex (m or f), then figure out name, email, sex
elif (line[-3] == ' ' and (line[-2] == 'm' or line[-2] == 'f')):
#find out the spaces. last space + 1 is sex
#start of line till second last space is profile name
#second last space to last space is profile email id
for i in range(ln):
if line[i] == ' ':
space_pos.append(i)
actor_name = ''
actor_email = ''
for i in range (0, space_pos[-2]):
actor_name = actor_name + line[i]
for i in range (space_pos[-2]+1,space_pos[-1]):
actor_email = actor_email + line[i]
#store into dict: email as key, name as value for ease of lookup
people[actor_email] = actor_name
#also store name email, sex into file_data list
file_data.append([actor_name,actor_email,line[-2]])
else:
#all other values just store into file_data list
#concat from position 0 thru len - 2. Note: len - 1 will be \n
for i in range (ln-1):
line_concat = line_concat + line[i]
#store this into file_data list
file_data.append(line_concat)
#now we are ready to print the profiles
print ('=' * 78)
print ('Profile Summary')
print ('=' * 78)
#print_line will determine what kind of data to print
#profile: name (sex | email id) will be printed
#desc: description from second line will be printed
#friends: will print the Friends(#) where # is number of friends
#if no friends, No friends yet... will be printed
#if there are friends, friend_count will be set to # of friends
#friend_list: will print the friends. email id will be looked up for print
#for every friend printed from friend_list, the counter will be reduced
#when the last friend is printed, we will set the print_line back to 'profile'
print_line = 'profile'
friend_count = 0
for i in file_data:
if print_line == 'profile':
print ('-' * 78)
print (f'{i[0]} ({i[2]} | {i[1]})')
print_line = 'desc'
elif print_line == 'desc':
print (f'- {i}')
print_line = 'friends'
elif print_line == 'friends':
if i == '0':
print ('- No friends yet...')
print_line = 'profile'
else:
print (f'- Friends ({i})')
friend_count = int(i)
print_line = 'friend_list'
elif print_line == 'friend_list':
if i in people:
print(f' {people[i]}')
else:
print(f' {i}')
if friend_count == 1:
print_line = 'profile'
else:
friend_count -= 1
print ('-' * 78)
print ('=' * 78)
output 將是:
==============================================================================
Profile Summary
==============================================================================
------------------------------------------------------------------------------
Fox Mulder (m | fox@findthetruth.com)
- The truth is out there!
- Friends (1)
Tony Stark
------------------------------------------------------------------------------
Tony Stark (m | tony@ironman.com)
- Saving the world is hard work - no time for friends.
- No friends yet...
------------------------------------------------------------------------------
Phil Dunphy (m | phil@dunphy.com)
- wtf? = why the face?
- Friends (2)
Robbie Gray
Fox Mulder
------------------------------------------------------------------------------
John Mayer (m | john@guitar.com)
- Waiting on the world to change!
- Friends (2)
Katy Perry
David Guetta
------------------------------------------------------------------------------
Katy Perry (f | katy@perry.com)
- Waiting on John to change.
- Friends (3)
John Mayer
David Guetta
Jimmy Fallon
------------------------------------------------------------------------------
David Guetta (m | dguetta@willworkwithanyone.org)
- Will collaborate with anyone who has a heartbeat.
- Friends (5)
Katy Perry
John Mayer
Tony Stark
Fox Mulder
Robbie Gray
------------------------------------------------------------------------------
Jimmy Fallon (m | jimmy@tonightshow.com)
- I wish I was as good as Letterman, thank goodness he's retiring.
- Friends (2)
Robbie Gray
Tony Stark
------------------------------------------------------------------------------
Robbie Gray (m | robbie@football.com)
- Training hard... can we win? Yes we Ken!
- Friends (4)
Jimmy Fallon
Fox Mulder
John Mayer
Tony Stark
------------------------------------------------------------------------------
==============================================================================
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.