让我们把这个任务转换成许多更小更容易解决的任务。
第一个函数
def string_to_tuple(person_string):
""" Converts a string into a tuple.
person_string must be in the following format: "first_name last_name salary"
A tuple of the following format is returned: (first_name, last_name, salary)
salary must be an int. If it can be a float change int to float
e.g.
>>> string_to_tuple("John Miller 100")
('John', 'Miller', 100)
"""
first_name, last_name, salary = person_string.split(" ")
return first_name, last_name, int(salary)
这个函数接受一个字符串在空格处分割它并返回一个元组。请注意,没有进行错误检查。您应该稍后检查输入是否有效。
第二个功能
def tuple_to_string(person_tuple):
"""Converts a tuple with person data into a string. This is is inverse function to `string_to_tuple`.
person_tuple must be in the following format: (first_name, last_name, salary)
A string of the following format is returned: "first_name last_name salary"
e.g.
>>> string_person = "John Miller 100"
>>> string_person_2 = tuple_to_string(string_to_tuple(string_person))
>>> string_person == string_person_2
True
>>> tuple_to_string(('John', 'Miller', 100))
'John Miller 100'
"""
string_person = " ".join(str(i) for i in person_tuple)
return string_person
在这里,您将一个元组连接回一个字符串。在加入之前,您需要将每个项目转换为字符串 (str(i))。
从文件中读取
要阅读,您应该使用with。这可确保文件在不再使用时始终关闭。
打开文件:
path_to_file = "my_file.txt"
with open(path_to_file, "r") as file:
content = file.read() # alternatives: file.readlines() or file.readline()
print(content) # To ensure the content was correctly read. Not needed in the later application
文件的路径必须相对于您当前的工作目录(脚本所在的位置)或绝对路径。
文件和路径的区别
文件的路径 (path_to_file) 和实际打开的文件 (file) 之间存在差异。路径可以由用户输入,您必须使用它来打开文件。用户无法输入文件对象。
>>> type(path_to_file)
<class 'str'>
>>> type(file)
<class '_io.TextIOWrapper'>
一个更容易理解的比较可能如下: 想想一个公共图书馆:图书馆有书,每本书都有一个标题。如果你想读一本书,你需要按书名找到这本书,拿一个样本打开它阅读。在此示例中,书名是文件名,书是文件。
从文件中读取并调用函数
现在最后一步是将所有东西放在一起。所以首先从文件中读取,然后调用之前创建的函数。读取取决于您的文件结构。我只是假设您在每一行中都有一个新人的数据。
with open(path_to_file, "r") as file:
for line in file.readlines():
tuple_person = string_to_tuple(line)
print(tuple_person) # verify output
如果您对某个部分有任何疑问,欢迎在 cmets 中提问。
编辑
根据文件内容调整
文件中的一行如下:切尔西右后卫大卫·扎帕科斯塔20,000,000
你需要扩展元组:
原文:first_name, last_name, salary
新:team, position, first_name, last_name, salary
注意:现在只需将薪水保留为 s 字符串,不要将其转换为 int 或 float。
原文:return first_name, last_name, int(salary)
新:return team, position, first_name, last_name, salary
和
原文:string_person = " ".join(str(i) for i in person_tuple)
新:string_person = " ".join(person_tuple)
资源