Python:使用管道作为分隔符分隔字符串

时间:2018-05-07 07:31:29

标签: python string split delimiter

我有一个字符串列表,数据由管道分隔,我想用管道作为分隔符拆分这些字符串。我尝试过使用x.split(' |'),但是它无效。这是我目前的代码:

 datas = []
    location = os.path.dirname(os.path.abspath(__file__))
    with open(filename, newline = '') as dar:
        for row in csv.reader(dar):
            datas.append(row)
    for x in datas:
       x[0].split('|')

这是我得到的输出片段:

['Crimson Rosella|-35.27454538728105|149.11596655088428|ACTON|2004-02-01|Aves|Psittaciformes|Psittacidae|Platycercus|Platycercus elegans|False'], ['Little cormorant|-35.27719826516971|149.11525904557516|Australian National University|2015-06-13|Aves|Pelecaniformes|Phalacrocoracidae|Phalacrocorax|Phalacrocorax melanoleucos|False']

提前致谢

3 个答案:

答案 0 :(得分:2)

您可以使用csv模块中的delimiter参数分隔|

<强>实施例

import csv
with open(filename) as dar:
    for row in csv.reader(dar, delimiter='|'):
        print(row)

<强>输出:

['Crimson Rosella', '-35.27454538728105', '149.11596655088428', 'ACTON', '2004-02-01', 'Aves', 'Psittaciformes', 'Psittacidae', 'Platycercus', 'Platycercus elegans', 'False']
['Little cormorant', '-35.27719826516971', '149.11525904557516', 'Australian National University', '2015-06-13', 'Aves', 'Pelecaniformes', 'Phalacrocoracidae', 'Phalacrocorax', 'Phalacrocorax melanoleucos', 'False']

答案 1 :(得分:0)

x[0].split('|')没有做任何事情,因为你没有对其结果做任何事情。也许你想这样做呢?

datas = [x.split('|') for x in datas]

你也可以一次性完成这一切:

datas.append(row.split('|'))

答案 2 :(得分:0)

这可能有效:

# x = text from line in datas, x[0] = first letter on the line
x = "Crimson Rosella|-35.27454538728105|149.11596655088428|ACTON|2004-02-01|Aves|Psittaciformes|Psittacidae|Platycercus|Platycercus elegans|False'], ['Little cormorant|-35.27719826516971|149.11525904557516|Australian National University|2015-06-13|Aves|Pelecaniformes|Phalacrocoracidae|Phalacrocorax|Phalacrocorax melanoleucos|False"

x = x.split('|')

print(x)