格式化文本文件中的字符串
Formatting strings from a text file
我正在尝试逐行格式化我从 .txt 文件中读取的文本。首先,我只是想弄清楚如何只打印一行,然后再尝试打印多行。我已经设法打印了一行的文本,但是当我尝试按照我希望的方式对其进行格式化时,在我尝试打印该行的最后一个字(使用索引 -1)后创建了一个新行.最后一个词是创建一个新行,所以我想我需要找到一种方法来将这些行作为单独的字符串读取,但我不确定。
这是我的程序的代码:
def makeTuple (employee):
myTuple = employee.split(" ")
payroll, salary, job_title, *othernames, surname = myTuple
myTuple = tuple(myTuple)
return(myTuple)
def printTuple (data):
employee_str = "{}, {} {:>8} {} {:>5}"
print(employee_str.format(data[-1], " ".join(data[3:-1], data[0], data[2], data[1]))
get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"
try:
text_file = open(path, "r")
except IOError:
print('The file could not be opened.')
exit()
record = text_file.readline()
myTuple = makeTuple(record)
printTuple(myTuple)
这是我正在读取的文本文件:
12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger
我现在得到的输出是:
Simpson
, Bart 12345 Consultant 55000
而我希望它看起来像:
Simpson, Bart 12345 Consultant 55000
您可以使用拆分和合并来完成:
s = '''Simpson
, Bart 12345 Consultant 55000'''
print(''.join(s.split('\n')))
您在 "Simpson"
后得到一个换行符,因为那是文本文件中的内容。
使用函数 strip()
(Documentation) 在阅读行时删除换行符。
更改以下一行代码,您的程序应该可以运行。
record = text_file.readline().strip()
我正在尝试逐行格式化我从 .txt 文件中读取的文本。首先,我只是想弄清楚如何只打印一行,然后再尝试打印多行。我已经设法打印了一行的文本,但是当我尝试按照我希望的方式对其进行格式化时,在我尝试打印该行的最后一个字(使用索引 -1)后创建了一个新行.最后一个词是创建一个新行,所以我想我需要找到一种方法来将这些行作为单独的字符串读取,但我不确定。
这是我的程序的代码:
def makeTuple (employee):
myTuple = employee.split(" ")
payroll, salary, job_title, *othernames, surname = myTuple
myTuple = tuple(myTuple)
return(myTuple)
def printTuple (data):
employee_str = "{}, {} {:>8} {} {:>5}"
print(employee_str.format(data[-1], " ".join(data[3:-1], data[0], data[2], data[1]))
get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"
try:
text_file = open(path, "r")
except IOError:
print('The file could not be opened.')
exit()
record = text_file.readline()
myTuple = makeTuple(record)
printTuple(myTuple)
这是我正在读取的文本文件:
12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger
我现在得到的输出是:
Simpson
, Bart 12345 Consultant 55000
而我希望它看起来像:
Simpson, Bart 12345 Consultant 55000
您可以使用拆分和合并来完成:
s = '''Simpson
, Bart 12345 Consultant 55000'''
print(''.join(s.split('\n')))
您在 "Simpson"
后得到一个换行符,因为那是文本文件中的内容。
使用函数 strip()
(Documentation) 在阅读行时删除换行符。
更改以下一行代码,您的程序应该可以运行。
record = text_file.readline().strip()