Python - 在一组字母上创建范围

时间:2017-07-22 16:07:44

标签: 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")

3 个答案:

答案 0 :(得分:0)

这是一个小例子:

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()

答案 1 :(得分:0)

格雷格。使用您在问题中提供的代码,这就是我要改变的内容:

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)

答案 2 :(得分:0)

由于您正在测试每个姓氏的首字母,因此字符串方法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)