【问题标题】:parsing file and appending string python解析文件并附加字符串python
【发布时间】:2022-01-03 12:22:46
【问题描述】:

假设我有一个文件:

This is the first line
Ages = ["young*","old*"] //This was the second line, I put a * on purpose
This is the third line

场景如下:

  1. 我知道文件中有“Ages”数组,但我不知道它的元素。
  2. 我现在想在每个元素后附加一个特定的字符串,比如“test*”,文件将变为:
This is the first line
Ages = ["young\*test\*","old\*test\*"] //This was the second line, I put a * on purpose
This is the third line

有什么帮助吗?

【问题讨论】:

  • 1) 读取文件。 2)找到那条线。 3) 使用ast.literal_evaljson.loads 解析列表文字。 4) 修改列表。 5)把它重新组合成一个字符串。 6) 将其全部写回文件中。

标签: python arrays parsing split element


【解决方案1】:

首先您需要以读写模式打开文件并将其全部读取到一个字符串中,然后我认为您最好的选择是使用正则表达式对您要替换的内容进行分组并替换它。然后将其写回文件。这将类似于以下内容:

pattern = re.compile(r'') # this would be your pattern
with open("filename.txt", "r+") as file:
    content = file.read() #all the content as string
    replaced = pattern.sub('the match group with your addition', content)
    file.seek(0) #the seek is necessary to return back to the start of the file
    file.write(replaced) # write the modified content to the file
    file.truncate() # truncate if there are any trailing parts from before

我认为这是一个家庭作业,所以我不会在那里完成正则表达式模式,但我会给出提示:

带有尾随 0 或更多空格的年龄 = 带有尾随 0 或更多空格的数组开放字符,其中包含内部数组元素的匹配组,以及表示每个元素结束的另一个内部组,然后您可以相应地替换它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 2018-07-18
    相关资源
    最近更新 更多