用Python在文件的列中写行 [英] Write rows in columns in file in Python
本文介绍了用Python在文件的列中写行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串形式的句子,看起来像这样:
I have sentences,in a form of a string, that look like this :
第一句话
hund
barked 4.51141770734e-07
bit 0.0673737226603
dog 0.932625826198
第二句话
hyi
biid 6.12323423324e-07
bok 0.0643253
dyfs 0.514586321
,我想将它们写到这样的文件的列中:
and I want to write them into columns into a file like this :
hund hyi
barked 4.51141770734e-07 biid 6.12323423324e-07
bit 0.0673737226603 bok 0.0643253
dog 0.932625826198 dyfs 0.514586321
而不是像这样:
hund
barked 4.51141770734e-07
bit 0.0673737226603
dog 0.932625826198
hyi
biid 6.12323423324e-07
bok 0.0643253
dyfs 0.514586321
有什么想法吗?
推荐答案
假设您有两个行列表,分别为lines1
和lines2
.如果您的字符串包含多个换行符,则可以通过调用.split('\n')
来创建行列表.
Suppose you have two lists of lines, lines1
and lines2
. If you have a string with multiple newlines, you can make a list of lines by calling .split('\n')
.
然后,您可以使用字符串格式将它们格式化为并行列:
Then, you can format them into parallel columns with string formatting:
lines = ['{:<40}{:<40}'.format(s1, s2) for s1, s2 in zip(lines1, lines2)]
示例:
a = ''' hund
barked 4.51141770734e-07
bit 0.0673737226603
dog 0.932625826198'''.split('\n')
b = ''' hyi
biid 6.12323423324e-07
bok 0.0643253
dyfs 0.514586321'''.split('\n')
lines = ['{0:<40}{1:<40}'.format(s1, s2) for s1, s2 in zip(a,b)]
print '\n'.join(lines)
输出:
hund hyi
barked 4.51141770734e-07 biid 6.12323423324e-07
bit 0.0673737226603 bok 0.0643253
dog 0.932625826198 dyfs 0.514586321
这篇关于用Python在文件的列中写行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文