import string
a_to_l = tuple (c for c in string.ascii_uppercase if c <= 'L')
surnames = ['Jacobson', 'Johnson', 'Williams', 'Abrahams', 'Putin']
with open('a_to_l.txt','w') as file_a_to_l, open('m_to_z.txt','w') as file_m_to_z:
for surname in surnames:
if surname.startswith(a_to_l):
print(surname, file=file_a_to_l)
else:
print(surname, file=file_m_to_z)
surnames = ['Jacobson', 'Johnson', 'Williams', 'Abrahams', 'Putin', 'Trump', 'Obama', 'Nixon']
with open('a_to_l_names.txt', 'w') as a_to_l, open('m_to_z.txt', 'w') as m_to_z:
for surname in surnames:
if ord(surname[0]) in range(ord('A'), ord('L') + 1):
print("a to l")
a_to_l.write(surname)
else:
print("m to z")
m_to_z.write(surname)
import re
a_to_l_pattern = r'^[a-lA-L]{1}'
with open('a_to_l_names.txt', 'w') as a_to_l, open('m_to_z.txt', 'w') as m_to_z:
for surname in surnames:
if re.search(a_to_l_pattern, surname):
print("a to l")
a_to_l.write(surname)
else:
print("m to z")
m_to_z.write(surname)
f = [i.strip('\n').split() for i in open('filename.txt')]
import string
letters = string.ascii_uppercase
group1 = letters[:12]
group2 = letters[12:]
first_group = [i[1] for i in f for b in group1 if i[1][0] == b] #contains list of surnames starting with letters in group1
second_group = [i[1] for i in f for b in group2 if i[1][0] == b] #contains list of surnames starting with letters in group2
file1 = open('other_file.txt', 'w')
file2 = open('other_file1.txt', 'w')
for a, b in zip(first_group, second_group):
file1.write(a+"\n")
file2.write(b+"\n")
file1.close()
file2.close()
因为您要测试每个姓氏的首字母,所以string方法
startswith
解释了代码的内容。你知道吗格雷格。使用您在问题中提供的代码,我将更改以下内容:
附加的
elif
条件是多余的。除非你希望名字不是以大写字母开头。必须使用ord()
获取字母的Unicode代码来检查范围。你知道吗正因为我喜欢尽可能地提供regex解决方案,即使你没有回复这篇文章,这里有另一种方法你可以使用。你知道吗
下面是一个小例子:
相关问题 更多 >
编程相关推荐