我怎样才能格式化每隔一行与前行合并? (在Python) [英] How can I format every other line to be merged with the line before it? (In Python)
问题描述
我一直在与美丽的汤一起提取网站的API数据在粉丝网站我建设使用。
我已经提取到的数据然而我无法格式化的文本文件。
查尔斯舞蹈
主泰温·兰尼斯特(S 02+)
娜塔莉·多莫
女王Margaery泰瑞尔(S 02+)
哈里·劳埃德
Viserys坦格利安(S 01)
马克·阿迪
国王劳勃·拜拉席恩(S 01)
阿尔菲·艾伦
席恩·葛雷乔伊
肖恩·宾
主艾德·史塔克(S 01)
我有几个文本文件,这样的节目。
我想有两个男演员和性格对后来用逗号输入分隔成一个数据库中的同一行。
查尔斯舞,主泰温·兰尼斯特(S 02+)
娜塔莉·多莫,皇后Margaery泰瑞尔(S 02+)
哈里·劳埃德,Viserys坦格利安(S 01)
马克·阿迪,国王劳勃·拜拉席恩(S 01)
阿尔菲·艾伦,席恩·葛雷乔伊
肖恩·宾,主艾德·史塔克(S 01)
如果任何人都可以提供任何帮助或指针将不胜AP preciated。
解决:
非常感谢Tdelaney和wnnmaw。你真正的大的MVP
高清的ReadLine(FP):
#阅读从文件中的一行,剥去新的生产线,提高Indexerror
文件#on结束
行= fp.readline()
如果没有行:
提高IndexError()
返回line.strip()开放(强制类型转换/ GOTcast.txt')为in_file中,开放('GOTcastFIXED.txt','W')为out_file:
尝试:
而真正的:
out_file.write(%S%S \\ n%(的ReadLine(in_file中)的ReadLine(in_file中)))
除非IndexError:
通过
这应该工作:
>>> LST = [一个,A,B,B,C,C]
>>>行= [,。加入(TUP)TUP用于以zip(LST [:: 2],LST [1:2])]
>>>线
['一,A,B,B','C,C']
您可以阅读文本文件是这样的:
开放(yourfile.txt,'R')为f:
线= f.readlines()
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()
这篇关于我怎样才能格式化每隔一行与前行合并? (在Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!