How can I format every other line to be merged with the line before it? (In Python)

你说的曾经没有我的故事 提交于 2020-01-01 19:22:13

问题


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

回答1:


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()



回答2:


So, you just want to read the file and combine every two lines into one. That's easy as long as you deal with a few details like stipping the new line character knowing when you've finished reading the file.

One way to solve this is to wrap the details in a function so that a simple for loop can do the rest.

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('infile.txt') as in_file, open('outfile.txt', 'w') as out_file:
    try:
        while True:
            out_file.write("%s, %s\n" % (readline(in_file), readline(in_file)))
    except IndexError:
        pass


来源:https://stackoverflow.com/questions/26869089/how-can-i-format-every-other-line-to-be-merged-with-the-line-before-it-in-pyth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!