简体   繁体   English

将文本文件内容读入列表

[英]Reading text file contents into a list

I have a text file containing: 我有一个包含以下内容的文本文件:

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

and I'm planning to read them into a list which outputs: 我打算将它们读入输出以下内容的列表:

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

I have written: 我已经写了:

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)

I almost managed to get the output i wanted but i couldn't figure out a way to separate the strings from: 我几乎设法获得了想要的输出,但是我想不出一种将字符串与以下内容分开的方法:

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

to

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

You can split the second element by comma. 您可以用逗号分隔第二个元素。

Demo 演示版

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)

Output: 输出:

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

Using Regex: 使用正则表达式:

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)

Output: 输出:

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

This is a one-liner with pandas. 这是与熊猫的一线客。 Your file is like a CSV file, just the separator character can be colon or comma, so we use a regex: 您的文件就像CSV文件一样,只是分隔符可以是冒号或逗号,因此我们使用正则表达式:

import pandas as pd

df = pd.read_csv('file.txt', header=None, sep=r'[:,]')

You can split a string by multiple delimiters : 您可以使用多个分隔符来分割字符串:

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

output: 输出:

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

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

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