例如,该函数目前正在工作,并将更改以下内容:
13126物理25000莎拉简史密斯
至:
史密斯,莎拉简13126物理25000
我试图使这个函数对外部文件中的文本行做同样的操作。外部文件中的行采用以下格式:
我试图调用我的函数,以与上面的示例相同的方式格式化这些行。我的代码目前打印一个输出,但它完全不正确。
这是我的密码:
print""
# To God be the Glory
Payroll = []
Department = []
Salary = []
name1 = []
name2 = []
possiblename3 = []
print ""
String = raw_input("Please enter the lecturers details: ")
def printFormat(String):
String = String.split()
Payroll.append(String[0])
Department.append(String[1])
Salary.append(String[2])
name1.append(String[3])
name2.append(String[4])
if len(String) == 6:
possiblename3.append(String[5])
print""
if possiblename3 != "":
print "%s,%s %s %s %s %s" % (','.join(possiblename3),', '.join(name1),', '.join(name2),', '.join(Payroll),', '.join(Department),', '.join(Salary))
else:
print "%s %s %s %s %s" % (', '.join(name1),', '.join(name2),', '.join(Payroll),', '.join(Department),', '.join(Salary))
print printFormat(String)
print ""
fname = input("Enter filename: ")
try :
f = open(fname)
myLine = f.readline()
while (len(myLine)>0) :
# print generates a newline so we do not want
# the newline from the string
print printFormat(myLine)
myLine = f.readline()
print ""
#f.close()
except IOError as e :
print("Problem opening file")发布于 2015-08-14 15:57:36
如果您只有5个或6个单词(取决于是否有中间名称),请将拆分字符串中的最后一个元素作为姓氏使用,即从元素3(即第一个名称切分到第二个单词)中使用,这样如果用户有中间名,您将得到一个单词或两个单词:
with open("in.txt") as f:
for line in f:
data = line.split()
print("{},{} {}".format(data[-1]," ".join(data[3:-1])," ".join(data[:3])))使用您的输入行,输出:
Simpson,Bart 12345 CSEE 35000
Potter,Harry 12346 CSEE 25000
Clown,Krusty The 12350 Economics 30000
Cameron,David 13123 Economics 55000
VanGaal,Louis 13124 Lingustics 40000
Smith,Sarah Jane 13126 Physics 25000
Blair,Tony 13127 History 35000您还可以使用csv模块读取和拆分数据:
import csv
with open("in.txt") as f:
r = csv.reader(f,delimiter=" ")
for row in r:
print("{},{} {}".format(row[-1]," ".join(row[3:-1])," ".join(row[:3])))还可以使用NamedTemporaryFile和shutil.move将重新格式化的数据写入原始文件:
import csv
from tempfile import NamedTemporaryFile
from shutil import move
with open("in.txt") as f, NamedTemporaryFile(delete=False,dir=".") as out:
wr = csv.writer(out)
r = csv.reader(f,delimiter=" ")
for row in r:
wr.writerow(['{},{}'.format(row[-1], " ".join(row[3:-1]))," ".join(row[:3])])之后的in.txt将类似于:
"Simpson,Bart",12345 CSEE 35000
"Potter,Harry",12346 CSEE 25000
"Clown,Krusty The",12350 Economics 30000
"Cameron,David",13123 Economics 55000
"VanGaal,Louis",13124 Lingustics 40000
"Smith,Sarah Jane",13126 Physics 25000
"Blair,Tony",13127 History 35000发布于 2015-08-14 18:42:21
为您的功能尝试这个:
def printFormat(String):
String = String.split()
lastname = String[-1]
firstnames = " ".join(String[3:-1])
name = ", ".join([lastname, firstnames])
otherstuff = " ".join(String[:3])
return " ".join([name, otherstuff])https://stackoverflow.com/questions/32013708
复制相似问题