我有一个包含数百名成员的列表,我想按名字、中间名和姓氏分隔这些成员,但其中一些成员具有前缀(用“P”表示)。所有可能的组合:
First Middle Last
P First Middle Last
First P Middle Last
P First p Middle Last
如何在 Python 中分隔名字(使用 P,如果可用)、中间名(使用 P,如果可用)和姓氏?这是我想出来的,但不太有效。
import csv
inPath = "input.txt"
outPath = "output.txt"
newlist = []
file = open(inPath, 'rU')
if file:
for line in file:
member = line.split()
newlist.append(member)
file.close()
else:
print "Error Opening File."
file = open(outPath, 'wb')
if file:
for i in range(len(newlist)):
print i, newlist[i][0] # Should get the First Name with Prefix
print i, newlist[i][1] # Should get the Middle Name with Prefix
print i, newlist[i][-1]
file.close()
else:
print "Error Opening File."
我想要的是:
- 获取名字和中间名及其前缀(如果有)
- 将每个(第一个、中间、最后一个)输出到单独的 txt 文件或单个 CSV 文件(首选)。
非常感谢您的帮助。
这个完整的测试脚本怎么样:
import sys
def process(file):
for line in file:
arr = line.split()
if not arr:
continue
last = arr.pop()
n = len(arr)
if n == 4:
first, middle = ' '.join(arr[:2]), ' '.join(arr[2:])
elif n == 3:
if arr[0] in ('M', 'Shk', 'BS'):
first, middle = ' '.join(arr[:2]), arr[-1]
else:
first, middle = arr[0], ' '.join(arr[1:])
elif n == 2:
first, middle = arr
else:
continue
print 'First: %r' % first
print 'Middle: %r' % middle
print 'Last: %r' % last
if __name__ == '__main__':
process(sys.stdin)
如果您在 Linux 上运行此程序,请输入示例行,然后按 Ctrl+D 表示输入结束。在 Windows 上,使用 Ctrl+Z 而不是 Ctrl+D。当然,您也可以通过管道输入文件。
以下输入文件:
First Middle Last
M First Middle Last
First Shk Middle Last
BS First M Middle Last
给出这个输出:
First: 'First'
Middle: 'Middle'
Last: 'Last'
First: 'M First'
Middle: 'Middle'
Last: 'Last'
First: 'First'
Middle: 'Shk Middle'
Last: 'Last'
First: 'BS First'
Middle: 'M Middle'
Last: 'Last'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)