【问题标题】:Select whitespace from first line only using regex in python仅在 python 中使用正则表达式从第一行中选择空格
【发布时间】:2015-05-08 13:49:22
【问题描述】:

我想匹配和替换 CSV 第一行中出现的空格。

例如,我只想用'_'替换第一行中的空格:

"product id","Region","Region Code" 
"888","North America","GEO123"

给予:

"product_id","Region","Region_Code" 
"888","North America","GEO123"

这是我目前的做法:

f1 = open('file1', 'r')
f2 = open('newfile', 'w')

for line in f1:
  f2.write(re.sub('([\s])+', '_', line))
f1.close()
f2.close()

替换整个文档中的所有空格。我该如何调整它以使其仅适用于文本的第一行?

【问题讨论】:

    标签: python regex csv


    【解决方案1】:

    \s 也匹配行尾的换行符。最好不要换!而且不需要自己做这么多。

    with open('file1', 'r') as f1, open('newfile', 'w') as f2:
        f2.write(re.sub('[ \t]+', '_', next(f1)))
        f2.writelines(f1)
    

    感谢with,您无需自己关闭文件(如果您有兴趣,请阅读“上下文管理器”)。 writelines 替换了你的循环。

    【讨论】:

    • 太棒了,如果我想同时执行多个正则表达式操作怎么办?例如。用管道替换逗号 |并应用上述正则表达式?
    • @pele88 你可以用一个正则表达式来做到这一点,但是匹配不同的东西是微不足道的,指定正确的替换 需要一个替换函数而不是一个简单的替换字符串。我只会做两个嵌套的re.sub。您还可以使用字符串的replace 方法,或者如果您有许多 一对一翻译,则使用字符串的translate 方法。
    【解决方案2】:
    f1 = open('file1', 'r')
    f2 = open('newfile', 'w')
    
    first_line = f1.readline()
    f2.write(re.sub('([\s])+', '_', first_line))
    for line in f1:
      f2.write(line)
    f1.close()
    f2.close()
    

    【讨论】:

      【解决方案3】:

      你可以使用枚举函数。

      f1 = open('file1', 'r')
      f2 = open('newfile', 'w')
      
      for i,line in enumerate(f1):
        if i == 0:
          f2.write(re.sub('[\t ]+', '_', line))
        else:
          f2.write(line)
      f1.close()
      f2.close()
      

      【讨论】:

      • if i == 0 听起来不太地道:)
      【解决方案4】:

      快速而肮脏(未经测试),并借用 Stefan 的回答:

      import re
      with open('file1', 'r') as f1, open('newfile', 'w') as f2:
          f2.write(re.sub("[\ ]+", "_", f1.read().strip(), f1.read().split("\n")[0].count(" "))
      

      【讨论】:

      • "[\ ]+"" +" 相同。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      • 2021-02-03
      • 1970-01-01
      相关资源
      最近更新 更多