您可以通过将linenumber modulo 5 与数字进行比较来识别每五行。在您的情况下,这应该是0,因为您想要第一行和第 6 行、第 11 行,...(请注意,python 以索引 0 开头)
要获取行号以及内容,您可以使用enumerate 遍历文件。
然后要丢弃字符串的name: 部分并保留后面的内容,您可以使用str.split()。
一个有效的实现可能如下所示:
# Create an empty list for the names
names = []
# Opening the file with "with" makes sure it is automatically closed even
# if the program encounters an Exception.
with open('name_data.txt', 'r') as file:
for lineno, line in enumerate(file):
# The lineno modulo 5 is zero for the first line and every fifth line thereafter.
if lineno % 5 == 0:
# Make sure it really starts with "name"
if not line.startswith('name'):
raise ValueError('line did not start with "name".')
# Split the line by the ":" and keep only what is coming after it.
# Using `maxsplit=1` makes sure you don't run into trouble if the name
# contains ":" as well (may be unnecessary but better safe than sorry!)
name = line.split(':', 1)[1]
# Remove any remaining whitespaces around the name
name = name.strip()
# Save the name in the list of names
names.append(name)
# print out the list of names
print(names)
您也可以使用带有 step 参数的 itertools.islice 来代替枚举:
from itertools import islice
with open('name_data.txt', 'r') as file:
for line in islice(file, None, None, 5):
... # like above except for the "if lineno % 5 == 0:" line
根据您的需要,您可以考虑使用re 模块来完全解析文件:
import re
# The regular expression
group = re.compile(r"name: (.+)\nfamily name: (.+)\nlocation: (.+)\nmembers: (.+)\n", flags=re.MULTILINE)
with open(filename, 'r') as file:
# Apply the regex to your file
all_data = re.findall(group, file)
# To get the names you just need the first element in each group:
firstnames = [item[0] for item in all_data]
对于您的示例,firstnames 将是 ['Kelo', 'Miko'],如果您使用 [item[1] for item in all_data],则类似,那么您将获得姓氏:['Lam', 'Naiton']。
要成功使用正则表达式,您必须确保它真正匹配您的文件布局,否则您会得到错误的结果。