python如何实现隔行_我怎样才能格式化每隔一行与前行合并? (在Python)

I have been working with beautiful soup to extract data from website APIs for use in a fan site I am building.

I have extracted the data into text files however I am having trouble formatting it.

Charles Dance

Lord Tywin Lannister (S 02+)

Natalie Dormer

Queen Margaery Tyrell (S 02+)

Harry Lloyd

Viserys Targaryen (S 01)

Mark Addy

King Robert Baratheon (S 01)

Alfie Allen

Theon Greyjoy

Sean Bean

Lord Eddard Stark (S 01)

I have several text files like this for shows.

I would like to have both the actor and character on the same line separated with commas for input into a database later.

Charles Dance , Lord Tywin Lannister (S 02+)

Natalie Dormer , Queen Margaery Tyrell (S 02+)

Harry Lloyd , Viserys Targaryen (S 01)

Mark Addy , King Robert Baratheon (S 01)

Alfie Allen , Theon Greyjoy

Sean Bean , Lord Eddard Stark (S 01)

If anyone could provide any assistance or pointers it would be greatly appreciated.

Solved:

Many thanks to Tdelaney and wnnmaw . you da real MVPs

def readline(fp):

#Read a line from a file, strip new line and raise Indexerror

#on end of file

line = fp.readline()

if not line:

raise IndexError()

return line.strip()

with open('Casts/GOTcast.txt') as in_file, open('GOTcastFIXED.txt', 'w') as out_file:

try:

while True:

out_file.write("%s, %s\n" % (readline(in_file), readline(in_file)))

except IndexError:

pass

解决方案

This ought to work:

>>> lst = ["a", "A", "b", "B", "c", "C"]

>>> lines = [" , ".join(tup) for tup in zip(lst[::2], lst[1::2])]

>>> lines

['a , A', 'b , B', 'c , C']

You can read your text file like this:

with open("yourfile.txt", 'r') as f:

lines = f.readlines()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值