Python文本文件修改

时间:2018-04-29 17:20:11

标签: python python-3.x parsing text-files

我正在尝试编写一个Python解析器来修改方括号内的文本 例如如果文本文件包含

TypeError: __call__() got multiple values for argument 'block'

1 个答案:

答案 0 :(得分:0)

您可以结合使用fileinputre模块。

这是代码(我已将评论内联):

def modify_text_inside_brackets(file_name, tag):
    with fileinput.input(files=(file_name), inplace=True) as text_file:
        for line in text_file:
            # split the line into groups
            matches = re.match(r"(.*)(\[.*\])(.*)", line)
            if matches:
                # get the text inside the brackets
                #   group(0): the entire matching line
                #   group(1): everything before the opening [
                #   group(2): [ .. ]
                #   group(3): everything after the closing ]
                text_inside_brackets = matches.group(2)[1:-1]
                # create a new [..] string with the prepended tag
                modified_text = "[{},{}]".format(tag, text_inside_brackets.strip())
                # replace the original [..] with the modified [..]
                modified_line = line.replace(matches.group(2), modified_text)
                # print out the modified line to the file
                print(modified_line, end="")
            else:
                print(line, end="")


modify_text_inside_brackets("input.txt", "TAG")

鉴于此“input.txt”:

[ 123,456]
[ city is beautiful]
This text has no brackets and should be unchanged.
It can also [ handle lines with inline] brackets.

代码会像这样修改它:

[TAG,123,456]
[TAG,city is beautiful]
This text has no brackets and should be unchanged.
It can also [TAG,handle lines with inline] brackets.

注意:

  • fileinput.input inplace=Trueprint输出重定向到文件
  • 目前还不清楚你的问题是<mystring><newtag>是什么,所以我只使用TAG
  • 根据您需要的输出格式修改"[{},{}]".format(tag, text_inside_brackets.strip())。例如,在您的问题中,[之后和]之前的空格在您的示例中不平衡且不一致,因此根据需要添加或strip()空格。
  • 您可以从this demo检查/测试正则表达式本身。
  • 我已将end=""传递给print,因为默认情况下print会添加换行符。