简体   繁体   English

如何使用python 3拆分列表?

[英]How to split a list using python 3?

I'm trying to combine multiple lines and split them by tabs :我正在尝试组合多行并按制表符拆分它们:

with open('combined.txt', "r") as f:
    print(' '.join(line.strip("\n").split("\t") for line in f))

but I am getting this error:但我收到此错误:

TypeError: sequence item 0: expected str instance, list found.类型错误:序列项 0:预期的 str 实例,找到列表。

input:输入:

azubi
arch=pc
mhz#2666
os=linux
ipv6net=auto

adrian
arch=pc
memory#4096
os=solaris11
osdist=opensolaris

desired output:所需的输出:

azubi arch=pc mhz#2666 os=linux ipv6net=auto <
adrian arch=pc memory#4096 os=solaris11 osdist=opensolaris

You can use this snippet to read and format your data, assuming that your data are seperated by a newline. 假定您的数据用换行符分隔,则可以使用此代码段读取和格式化数据。

Outputs = list()
Output = str()
with open('Test.txt', "r") as f:
    for line in f:
        line = line.strip()
        if(len(line)):
            Output += "{} ".format(line)
        else:
            Outputs.append(Output)
            Output = str()

for Output in Outputs:
    print("".join(Output))

This gives the output: 这给出了输出:

azubi arch=pc mhz#2666 os=linux ipv6net=auto 
adrian arch=pc memory#4096 os=solaris11 osdist=opensolaris 

check the position of your brackets, I suppose it should be 检查一下支架的位置,我想应该

with open(file, "r") as f:
    print(' '.join(line.strip("\n").split("\t")) for line in f)

however, (' '.join(line.strip("\\n").split("\\t")) for line in f) will return a generator , print() then just prints information on the generator , like <generator object <genexpr> at 0x0000020B62EE1A20> . 但是, (' '.join(line.strip("\\n").split("\\t")) for line in f)将返回一个generatorprint()然后仅在该generator上打印信息,例如<generator object <genexpr> at 0x0000020B62EE1A20> I guess that's not what you want. 我想那不是你想要的。 You could use instead: 您可以改用:

with open(file, "r") as f:
    for line in f:
        print(' '.join(line.strip("\n").split("\t")))

EDIT: a quick fix to get the output you want, in two lines: 编辑:快速获得两行所需的输出:

with open(file, "r") as f:
    print(' '.join([line.strip() if line != '\n' else line for line in f]).replace('\n ', '\n'))

pretty hacky though, if you have to load multiple of such files, on a regular basis, I suggest writing a proper file parser. 不过,如果您必须定期加载多个此类文件,我建议您编写一个适当的文件解析器。

So whilst I think the other answers have solved the error, they aren't giving you the intended output. 因此,尽管我认为其他答案已经解决了错误,但它们并没有为您提供预期的输出。

I am making the assumption that the text that forms 1 line in the output is always separated by a single blank line, as in your sample input. 我假设与示例输入一样,在输出中形成1行的文本始终由单个空白行分隔。

I have two possible solutions: 我有两种可能的解决方案:

Method 1 : 方法1

with open('test.txt', 'r') as in_f:
    content=in_f.read()


content2 = content.splitlines()
new_lines = []
while content2:
    try:
        split_idx = content2.index('')
        new_lines.append(content2[0:split_idx])
        content2 = content2[split_idx+1:]
    except ValueError as e:
        new_lines.append(content2)
        content2 = False

for line in new_lines:
    print(' '.join(line))

azubi arch=pc mhz#2666 os=linux ipv6net=auto
adrian arch=pc memory#4096 os=solaris11 osdist=opensolaris

Method 2 : 方法2

with open('test.txt', 'r') as in_f:
    content=in_f.read()

content2 = content.splitlines()

size = len(content2) 
idx_list = [idx + 1 for idx, val in enumerate(content2) if val == '']

res = [content2[i: j] for i, j 
    in zip([0] + idx_list, idx_list + 
    ([size] if idx_list[-1] != size else []))] 

for line in res:
    print(' '.join(line).strip())

azubi arch=pc mhz#2666 os=linux ipv6net=auto
adrian arch=pc memory#4096 os=solaris11 osdist=opensolaris

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM