我有以下格式的文本文件:1. AUTHOR1
(blank line, with a carriage return)
Citation1
2. AUTHOR2
(blank line, with a carriage return)
Citation2
(...)
也就是说,在这个文件中,有些行以整数开头,然后是点、空格和表示作者姓名的文本;这些行之后是空行(包括回车符),然后是以字母字符开头的文本行(文章或书籍引用)。
我想把这个文件读入一个Python列表,加入作者的名字和引文,这样每个列表元素都是这样的:
['AUTHOR1引文1','AUTHOR2引文2','…']
这看起来是一个简单的编程问题,但我无法找到解决方案。我的尝试如下:
articles = []
with open("sample.txt", "rb") as infile:
while True:
text = infile.readline()
if not text: break
authors = ""
citation = ""
if text == '\n': continue
if text[0].isdigit():
authors = text.strip('\n')
else:
citation = text.strip('\n'
articles.append(authors+' '+citation)
但是文章列表将作者和引文存储为单独的元素!
提前感谢任何帮助解决这个棘手的问题…:-(
最佳答案:
假设输入文件结构:"""
1. AUTHOR1
Citation1
2. AUTHOR2
Citation2
"""
不会改变,我将使用readlines()和切片:
with open('sample.txt', 'r') as infile:
lines = infile.readlines()
if lines:
lines = filter( lambda x : x != '\n', lines ) # remove empty lines
auth = map( lambda x : x.strip().split('.')[-1].strip(), lines[0::2] )
cita = map( lambda x : x.strip(), lines[1::2] )
result = [ '%s %s'%(auth[i], cita[i]) for i in xrange( len( auth )) ]
print result
# ['AUTHOR1 Citation1', 'AUTHOR2 Citation2']