Python: 如果名称由逗号分隔并在不同的行中,如何从文件中读取名称?

Python: How to read names from a file if the names are separated by a comma and on separate lines?

我需要修改当前读取用户名分行的文件的代码。如果名称以逗号分隔并在不同的行中,它需要读取文件。

我目前需要修改的代码是:

inFileName = input("Enter the file name with people's names: ")
outFileName = input("Enter the file name to write user names to: ")

inFile = open(inFileName, "r")
outFile = open(outFileName, "w")

namesSeq = inFile.readlines()

for name in namesSeq:
    splitName = name.rstrip().split (",")

    firstName = splitName[0]
    lastName = splitName [1]

    userName = firstName[:0] + lastName[:7]
    userName = userName.lower()

    print (userName, file=outFile)

inFile.close()
outFile.close()

我需要修改它以使用此文件:

Earl Anthony,Pete Weber, Mark Roth, Mike Aulby, Norm Duke
Tori Romeo, Jeri Edwards, Lynda Barnes, Nikki Gianulias, Cara Honeychurch

看起来像这样:

anthony
weber
roth
aulby
duke
romeo
edwards
barnes
gianuli
honeych

尝试以下操作:

inFileName = input("Enter the file name with people's names: ")
outFileName = input("Enter the file name to write user names to: ")

inFile = open(inFileName, "r")
outFile = open(outFileName, "w")

for line in inFile:
    names = line.split(",")
    for name in names:
        userName = name.split()[1].lower()[:8]
        print(userName, file=outFile)

inFile.close()
outFile.close()

您可以使用re模块的split()功能来分隔您inFile的所有名称。然后你可以遍历 split() 操作的结果列表,将每个用户名写入 outFile.

inFile = open(inFileName)
outFile = open(outFileName, 'w')

data = in_file.read()
for name in re.split(',|\n', data):
    print(name.split()[-1].lower()[:7], file=outFile)

inFile.close()
outFile.close()