所以基本上我正在尝试制作一个程序,从一个文件中获取名称的格式" Smith,Robert" 并制作一个看起来像" RobeSmit,Smith,Robert,RobertSmith,(随机生成的密码)"的输出。我已经完成所有工作,但它只能做一个名字,我需要它做的文件中有多少例如:Smith,Robert Boe,Joe
这就是我所拥有的:
import random
def readFile():
f_input = open("myFile.txt", "r")
string = f_input.read()
f_input.close
return string
def firstFour(string):
lastNameFour, firstNameFour = string.split(",")
userName = (str(firstNameFour[1:5]) + str(lastNameFour[0:4]))
return userName
def nameArrangement(string):
lastName, firstName = string.split(",")
names = (str(lastName)) + "," + str(firstName) + "," + str(firstName) + str(lastName)
return names
def passwordGen():
alphabet = "abcdefghijkmnopqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWXYZ!@#$%^&*()-=_+\][|}{;?/.,<>"
length = 7
password = " "
for i in range (length):
nextChr = random.randrange(len(alphabet))
password = password + alphabet[nextChr]
return password
def putItTogether(userName, names, password):
output = userName + ", " + names + ", " + password
print (output)
def main():
string = readFile()
userName = firstFour(string)
names = nameArrangement(string)
character = passwordGen()
putItTogether(userName, names, character)
if __name__ == '__main__':
main()`
任何帮助将不胜感激。谢谢!
答案 0 :(得分:0)
你main
函数应该是:
def main():
with open("myFile.txt", "r") as f:
for string in f:
userName = firstFour(string)
names = nameArrangement(string)
character = passwordGen()
putItTogether(userName, names, character)
答案 1 :(得分:0)
让我们检查您的代码并将阅读线嵌入其中。
更改readFile
以返回所有行:
def readFile():
# with is used when a resource is only needed in a certain context.
# we'll use it for opening files so they close automatically.
with open("myFile.txt", "r") as f:
return f.readlines()
写saveFile
以在文件中存储已处理的行:
def writefile(lines):
with open("myFile.txt", "w") as f:
f.writelines(lines)
编写processLine
以包装单行处理,返回结果(不需要putItTogether
):
def processLine(line):
userName = firstFour(string)
names = nameArrangement(string)
character = passwordGen()
return userName + ", " + names + ", " + password
现在使用map
将处理应用于所有行(也可以执行list comprehension),然后将其写回:
def main()
writeFile(map(processLine, readFile()))
提示:这不是很普遍,想一想从值中抽象动作的方法。例如,readFile
应该读取文件而不是特定文件。它应该定义为def readFile(filename)
。