【问题标题】:Python re.sub specific syntaxPython re.sub 特定语法
【发布时间】:2018-04-29 12:17:57
【问题描述】:

我正在用 python 编写一个脚本来替换 Linux 文件中的特定行。假设我在 /home 目录中有一个名为 hi 的文件,其中包含:

hi 873840

这是我的脚本:

#! /usr/bin/env python

import re

fp = open("/home/hi","w")
re.sub(r"hi+", "hi 90", fp)

我想要的结果是:

hi 90

但是,当我运行它时,我得到了这个错误,并且 hi 文件最终被 balnk:

Traceback (most recent call last):
  File "./script.py", line 6, in <module>
    re.sub(r"hi+", "hi 90", fp)
  File "/usr/lib/python2.7/re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
 TypeError: expected string or buffer

我的语法有问题吗? 谢谢

【问题讨论】:

标签: python linux scripting


【解决方案1】:

您应该以读取模式打开文件。 re.sub 需要三个参数,pattern, repl, string。问题是您传递的第三个参数是文件指针。
例如:

import re
with open('/home/hi', 'r', encoding='utf-8') as infile:
    for line in infile:
       print(re.sub(r"hi+", "hi 90", line.strip()))

【讨论】:

    【解决方案2】:

    使用"r" more 读取文件,"w" 模式将创建空文件进行写入。 .readline() 将获取字符串并将其传递给re.sub()r" .*" 将在 'space' 字符之后返回您要替换的字符串。我假设'hi 873840' 是您文件中唯一的文本,而您想要的输出只有'hi 90'

    echo "hi 873840" > hi.txt
    
    python3.6
    
    import re
    fp = open("hi.txt", "r")
    print(re.sub(r" .*", " 90", fp.readline()))
    

    【讨论】:

    • 描述您提出的解决方案的文字将对提出问题的人有用。
    • 感谢您的提醒和建议。 stackoverflow 的新手
    猜你喜欢
    • 2023-04-07
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多