0

我有一个文本文件,其中包含:

1:PAPER TOWNS,TOMORROWLAND
2:ENTOURAGE,JUPITER ASCENDING

我打算将它们读入一个输出列表:

[[1,'PAPERTOWNS','TOMORROWLAND'],[2,'ENTOURAGE','JUPITERASCENDING']]

我已经写了:

def read_file():
    fileName = "testing.txt"
    testFile = open(fileName)
    table = []

    for line in testFile:
        contents = line.strip().split(':')
        contents[0] = int(contents[0])
        contents[1] = contents[1].replace(' ','')
        table.append(contents)
    print(table)

我几乎设法得到了我想要的输出,但我想不出一种方法来分离字符串:

[[1,'PAPERTOWNS,TOMORROWLAND'],[2,'ENTOURAGE,JUPITERASCENDING']]

[[1,'PAPERTOWNS','TOMORROWLAND'],[2,'ENTOURAGE','JUPITERASCENDING']]
4

3 回答 3

1

您可以用逗号分隔第二个元素。

演示

def read_file():
    fileName = "testing.txt"
    testFile = open(fileName)
    table = []

    for line in testFile:
        contents = line.strip().split(':')
        table.append([int(contents[0])] + contents[1].split(","))
    print(table)

输出:

[[1, 'PAPER TOWNS', 'TOMORROWLAND'], [2, 'ENTOURAGE', 'JUPITER ASCENDING']]

使用正则表达式:

import re
def read_file():
    fileName = "testing.txt"
    testFile = open(fileName)
    table = []

    for line in testFile:
        contents = re.split("[,:]+", line.strip())
        table.append(contents)
    print(table)

输出:

[['1', 'PAPER TOWNS', 'TOMORROWLAND'], ['2', 'ENTOURAGE', 'JUPITER ASCENDING']]
于 2018-03-15T03:28:14.630 回答
0

这是与熊猫的单线。您的文件就像一个 CSV 文件,只是分隔符可以是冒号或逗号,所以我们使用正则表达式:

import pandas as pd

df = pd.read_csv('file.txt', header=None, sep=r'[:,]')
于 2018-03-15T03:33:45.300 回答
0

您可以通过多个分隔符拆分字符串:

import re
print([[int(re.split(':|,', line.strip())[0])]+re.split(':|,', line.strip())[1:] for line in open('text_file','r')])

输出:

[[1, 'PAPER TOWNS', 'TOMORROWLAND'], [2, 'ENTOURAGE', 'JUPITER ASCENDING']]
于 2018-03-15T04:38:39.470 回答