【问题标题】:Read file and strip \n and split for list读取文件并剥离 \n 并拆分为列表
【发布时间】:2017-11-03 20:46:13
【问题描述】:

我有一个作业,我必须在其中读取文件“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() 打印出来。

【问题讨论】:

    标签: python python-3.x split strip


    【解决方案1】:

    阅读时可以使用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
    

    【讨论】:

    • 非常感谢您抽出宝贵时间向我解释。
    【解决方案2】:

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

    在您的代码上构建,在这里您可以如何进行

    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]
    

    【讨论】:

      【解决方案3】:

      使用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']
      

      【讨论】:

        【解决方案4】:

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

        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']
        

        【讨论】:

        • 或者只使用拆分功能。 a=re.split(",\n", tulokset)
        猜你喜欢
        • 2023-03-25
        • 1970-01-01
        • 2017-02-11
        • 1970-01-01
        • 2016-08-01
        • 1970-01-01
        • 2011-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多