我如何能够遍历文本文件的每一行并使用Python将作者的名字复制到列表中?我正在处理的文本文件包含以下引号,每个引号末尾都有作者的姓名:
权力容易腐化,绝对的权力绝对腐化。-阿克顿勋爵--亨利·B·亚当斯一生中的一个朋友是多的;两个是多的;三个是不可能的。--亨利·B·亚当斯
发布于 2014-06-01 12:23:25
试试这个:
authors_list = []
with open('file.txt', 'r') as f:
for line in f:
text = line.rstrip('\n').split(" --- ")
if len(text) > 1:
authors_list.append(text[1])发布于 2014-06-01 13:33:44
使用正则表达式,您可以这样做:
import re
import string
with open('text.txt') as f:
txt = f.readlines()
authors = re.findall('(?<=---).*?(?=\n)', '\n'.join(txt))
authors = map(string.strip, authors)发布于 2014-06-01 13:33:59
下面是一个基于生成器的解决方案,以获得一些乐趣:
# Generate stream manipulators
def strip(stream):
"""Strips whitespace from stream entries"""
for entry in stream:
yield entry.strip()
def index(i, stream):
"""Takes the i-th element from the stream entries"""
for entry in stream:
yield entry[i]
def split(token, stream):
"""Splits the entries in the stream based based on the token"""
for entry in stream:
yield entry.split(token)
# Actual function to do the work
def authors(filename):
"""Returns a list of the authors from the file format"""
for entry in strip(index(1, split('---', open(filename)))):
yield entry
print list(authors('file.txt'))基于生成器/过滤/管道的解决方案可以很好地完成这类任务。
https://stackoverflow.com/questions/23979764
复制相似问题