【问题标题】:Remove all characters before comma of every line in a file in python删除python文件中每一行逗号前的所有字符
【发布时间】:2012-03-09 19:40:10
【问题描述】:

我需要 python 中的一个小函数,它可以读取文件,然后删除所有字符,包括逗号字符。例如以下两行文件:

hello,my name is
john,john, mary

应该是:

my name is
john, mary

【问题讨论】:

    标签: python file io


    【解决方案1】:

    已建议您使用re.split();但是,str 的常规 split() 方法也应该足够了:

    with open('new_file', 'w') as f_out, open('my_file') as f_in:
        for line in f_in:
            new_str = ','.join(line.split(',')[1:])
            f_out.write(new_str)
    

    【讨论】:

    • 常规 split 甚至比您在此处显示的更好,因为您可以将最大出现次数指定为第二个参数:new_str = line.split(',', 1)[1]
    • @JohnY - 你的版本并不好,因为它在不存在逗号时会失败。
    【解决方案2】:

    你想要的是Regular Expressions。具体来说,split 应该可以正常工作。

    vals=re.split(',',string,1)

    【讨论】:

    • 不要分裂头发(双关语非常有意),但调用 split 与使用正则表达式不同。我的意思是,通过在给定字符输入上拆分字符串定义的语言是常规的,当然,但是正则表达式是表达常规语言的特定方式。你可以很容易地说“你想要的就是 DFA”,而且你也只说对了一半。
    【解决方案3】:

    还有:

    line = 'hello,my name is'
    line[line.find(',')+1 :  ]     #find position of first ',' and slice from there
    >>> 'my name is'
    

    【讨论】:

      【解决方案4】:

      使用partition

      >>> foo = 'hello, my name is'
      >>> foo.partition(',')[2]
      ' my name is'
      >>> foo = 'john, john, mary'
      >>> foo.partition(',')[2]
      ' john, mary'
      >>> foo = 'test,'
      >>> foo.partition(',')[2]
      ''
      >>> foo = 'bar'
      >>> foo.partition(',')[2]
      ''
      

      【讨论】:

      • 这在',' 不存在的情况下有点混乱!
      • @vikki:这取决于 OP 的意思是“删除所有字符,包括逗号”。这可以解释为意味着没有任何逗号的行应该删除所有字符(这就是这个答案的作用)。但是,您指出我们应该考虑边缘情况是件好事,因为这在现实世界中经常困扰我们。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      相关资源
      最近更新 更多