【问题标题】:FileInput as line versus fileinput as stringFileInput 作为行与 fileinput 作为字符串
【发布时间】:2015-10-11 03:46:00
【问题描述】:

我有一个文件列表,我想用正则表达式替换迭代,一些在单独的行上,一些需要多行匹配。

我能够遍历文件列表中的行并使用此方法写入磁盘。

import fileinput, re

ListFiles = ['in/spam.txt', 'in/eggs.txt', 'in/spam2.txt', 'in/eggs2.txt', 
'in/spam3.txt', 'in/eggs3.txt', 'in/spam4.txt', 'in/eggs4.txt',
'in/spam5.txt', 'in/eggs5.txt']

with fileinput.input(files=(ListFiles), inplace=True, backup='.bak') as f:
    for line in f:
        line = re.sub(r'this','that', line)
        print(line, end='')

现在我想将f 中的输出行收集为一个字符串,我可以为此运行多行 RegEx 例程。

我尝试了with(open),我已经能够将它与正则表达式一起使用单个文件,但它不接受列表作为参数,只有文件名。

with open("spam.txt", "w") as f: # sample other use, list not allowed here.
    data = f.read()
    data = re.sub(r'sample', r'sample2', data)
    print(data, file=f)

我尝试将f作为一个字符串收集到新的变量数据中,如下:

data = f(str)
data = re.sub(r'\\sc\{(.*?)\}', r'<hi rend="small_caps">\1</hi>', data) ## Ignore that this not multiline Regex for sample purposes only.
print(data)

但这会产生错误,即 FileInput 不可调用。

有没有一种方法可以迭代并将 RegEx 应用于文件作为行,以及作为与语句相同的字符串的相同文件?

【问题讨论】:

  • 请注意,如果您只想将text1 替换为text2,如line = re.sub(r'this','that', line),您可以简单地使用line = line.replace('this', 'that')
  • 您是要跨文件进行多行匹配,还是只在每个文件内进行匹配?如果是后者,为什么不遍历文件并单独读取每个文件? fileinput 只是一个简化打开和读取一堆文件的便利类。它使用常规的openreadline 函数。
  • 我使用的是更复杂的正则表达式,所以 line.replace 不够健壮。为了清楚起见,我将它们排除在外。 J. F. Sebastian 在下面给出了一个很好的解决方案。

标签: python regex python-3.x


【解决方案1】:

如果可以将单个文件作为一个整体读入内存然后在文件列表中执行多行替换,您可以一次处理一个文件:

for filename in ListFiles:
    with open(filename) as file: 
        text = file.read() # read file into memory
    text = text.replace('sample\n1', 'sample2') # make replacements
    with open(filename, 'w') as file: 
        file.write(text) # rewrite the file

【讨论】:

  • 非常感谢 J. F. 塞巴斯蒂安。作为with file.input 的附属命令,与for line in f: 处于同一级别,您解决了困扰我好几天的问题。现在开始写我的 70 个左右的 RegEx。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
  • 2017-01-13
  • 1970-01-01
  • 2011-06-06
相关资源
最近更新 更多