Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 读取文件并剥离\n和拆分列表_Python_Python 3.x_Split_Strip - Fatal编程技术网

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

Python 读取文件并剥离\n和拆分列表,python,python-3.x,split,strip,Python,Python 3.x,Split,Strip,我有一个作业,其中我必须阅读一个文件“words.csv”: Hemuli,Muumipapa,13,4 阿巴斯,芬里兹,6,6 我应该把它打印出来如下: Hemuli 13-4 muumipapa 阿巴斯6-6芬里兹酒店 到目前为止,我的代码是: def nayta_tulokset(words): with open(words) as tulos: tulokset = tulos.read() a = tulokset.split(",")

我有一个作业,其中我必须阅读一个文件“words.csv”:

Hemuli,Muumipapa,13,4
阿巴斯,芬里兹,6,6
我应该把它打印出来如下:

Hemuli 13-4 muumipapa
阿巴斯6-6芬里兹酒店
到目前为止,我的代码是:

def nayta_tulokset(words):
    with open(words) as tulos:
        tulokset = tulos.read()
        a = tulokset.split(",")
        print(a)
这给了我以下
列表

['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']
然后拆分字符串
。拆分(',)


为了获得所需的输出,需要分别读取每一行并按预期打印出来

建立,在你的代码,这里你可以如何继续

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.read().split('\n')
,而不是使用
tulos.readlines()
,这将负责将文件读入行列表。因此,重构后,代码将如下所示:

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]

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

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())))
所以


或者只使用split函数
a=re.split(“,\n”,tulokset)
非常感谢您花时间向我解释这一点。
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']