读取文件并剥离 \n 并拆分列表

Read file and strip \n and split for list

我有一个作业,我必须在其中读取一个文件 "words.csv":

Hemuli,Muumipappa,13,4
Abbath,Fenriz,6,6

我应该打印如下:

Hemuli 13 - 4 Muumipappa
Abbath 6 - 6 Fenriz

到目前为止我的代码:

def nayta_tulokset(words):
    with open(words) as tulos:
        tulokset = tulos.read()
        a = tulokset.split(",")
        print(a)

这给了我以下 list:

['Hemuli', 'Muumipappa', '13', '4\nAbbath', 'Fenriz', '6', '6']

这正是我想要的,但我该如何继续剥离 \n? “4”和 "Abbath" 应该在它们自己的索引之一中。似乎无法弄清楚...之后我可以使用索引并使用 format() 打印出来。

您可能想要使用正则表达式。像这样:

import re

def nayta_tulokset(words):
    with open(words) as tulos:
        tulokset = tulos.read()
        #a = re.findall(r"[\w']+", tulokset)
        a = re.split(",\n", tulokset)

这应该给你:

['Hemuli', 'Muumipappa', '13', '4', 'Abbath', 'Fenriz', '6', '6']

阅读时可以使用splitlines()

def nayta_tulokset(words):
    with open(words) as tulos:
        return tulos.read().splitlines()

# output: ['Hemuli,Muumipappa,13,4', 'Abbath,Fenriz,6,6']

然后拆分字符串.split(',')

for i in nayta_tulokset(words):
    _f = i.split(",")
    print("{} {} - {} {}".format(_f[0], _f[-2], _f[-1], _f[1]))

# Hemuli 13 - 4 Muumipappa
# Abbath 6 - 6 Fenriz

为了得到你想要的输出,你需要分别读取每一行并按预期打印出来。

在你的代码上构建,这里是你如何继续

def nayta_tulokset(words):
    with open(words) as tulos:
        for line in tulos.read().split('\n'):
           a = line.split(",")
           print("{} {} - {} {}".format(a[0], a[2], a[3], a[1]))

您可以使用 tulos.readlines() 而不是使用 tulos.read().split('\n'),它将负责将您的文件读入行列表。所以重构之后,代码会是这样的:

def nayta_tulokset(words):
    with open(words) as tulos:
        for line in tulos.readlines():
           a = line.split(",")
           print("{} {} - {} {}".format(a[0], a[2], a[3], a[1]))

更多详情: 我想代码中唯一有点模棱两可的部分如下:

"{} {} - {} {}".format(a[0], a[2], a[3], a[1])

相当于以下字符串连接:

 a[0] +" " + a[2] +" - " + a[3] + " " +a[1]

使用 list comprehension 和上述字符串格式的解决方案可能是:

def nayta_tulokset(words):
    with open(words, 'r') as f:
        return list(map(lambda x:"{} {} - {} {}".format(x[0],x[2],x[3],x[1]), map(lambda x:x.split(','),f.read().split())))

所以

nayta_tulokset('words.csv')
['Hemuli 13 - 4 Muumipappa', 'Abbath 6 - 6 Fenriz']