python是结构化语言_在Python中读取结构化文本文件

我有以下格式的文本文件: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']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值