Python-在一组字母上创建一个范围
我有一个名字列表,我需要把所有以a到L开头的姓氏写在一个文件中,把其他以M到Z开头的姓氏写在另一个文件中。有什么想法吗?谢谢Python-在一组字母上创建一个范围,python,Python,我有一个名字列表,我需要把所有以a到L开头的姓氏写在一个文件中,把其他以M到Z开头的姓氏写在另一个文件中。有什么想法吗?谢谢 if surname[0] in range(A, L): print("a to l") elif surname[0] in range(M, Z): print("m to z") 下面是一个小例子: f = [i.strip('\n').split() for i in open('filename.txt')] import string
if surname[0] in range(A, L):
print("a to l")
elif surname[0] in range(M, Z):
print("m to z")
下面是一个小例子:
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()
格雷格。使用您在问题中提供的代码,我将更改以下内容:
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)
附加的elif
条件是多余的。除非你希望名字的开头不是大写字母。您必须使用ord()
获取字母的Unicode代码以检查范围
正因为我喜欢尽可能地提供正则表达式解决方案,即使你没有回复这篇文章,这里有另一种方法你可以使用
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)
由于您正在测试每个姓氏的首字母,因此string方法
startswith
解释了您的代码是关于什么的
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)
导入字符串
a_to_l=元组(c代表字符串中的c.ascii_大写字母,如果c你应该在你的问题中添加一些代码!你有什么想法吗?尝试了什么?>>ord('Lincoln'[0])范围(ord('a'),ord('l'))
givesFalse
啊,很好的理解。我没有彻底测试它。我会更新答案。我理解这个方法,它看起来很完美,但我没有真正理解“startswith”部分。目的是代码尽可能接近你用英语说的方式。所以,“如果姓氏
以'A'到'L'开头,那么…”被编码为如果姓氏。以(A_到L)开头:
恐怕我不能说得更清楚了。