【问题标题】:Trying to copy/paste text between Start and End points, transpose, and swap data points尝试在起点和终点之间复制/粘贴文本、转置和交换数据点
【发布时间】:2018-10-21 02:34:02
【问题描述】:

我有一些代码可以将大文件中的复制/粘贴到我需要的已解析文件中。这是一个工作脚本。

with open('C:\\Users\\Excel\\Desktop\\test_in.txt') as infile, open('C:\\Users\\Excel\\Desktop\\test_out.txt', 'w') as outfile:
    copy = False
    for line in infile:
        if line.strip() == "Start":
            copy = True
        elif line.strip() == "End":
            copy = False
        elif copy:
            outfile.write(line)

现在,我试图弄清楚如何转置每个测试块,并多次交换相邻的数据点。也许这需要一个数据帧,我不太确定。

这是一张之前的图片。

这是一张后照。

这是我的示例文本。

file name
file type
file size
Start
        - data_type: STRING
          name: Operation
        - data_type: STRING
          name: SNL_Institution_Key
        - data_type: INTEGER
          name: SNL_Funding_Key
End
        - data_type: STRING
          name: Operation
        - data_type: STRING
          name: SNL_Institution_Key
        - data_type: INTEGER
          name: SNL_Funding_Key
Start
        - data_type: STRING
          name: SEDOL_NULL
        - data_type: STRING
          name: Ticker
        - data_type: DATETIME
          name: Date_of_Closing_Price
End 

在我看来,这在 Python 中很难做到。如果做这一切太难了,请告诉我。 Python 可能不是适合这项工作的工具。我对 Python 的了解还不够,无法确定这是否是正确的方法。感谢您的宝贵时间。

【问题讨论】:

  • 预期结果是什么
  • 如果您在拆分后阅读每一行,您应该能够对其进行切片并反转位置,然后添加额外的字符串并加入它们。绝对可行。
  • @Serge;这是后图像。 @伯纳德;绝对可行。是的,是的,我相信。我的 python 技能还不够完善,无法为此编写解决方案。我知道 Python 非常强大,但你需要知道如何利用这种力量,否则它就被浪费了。
  • 一种粗略的慢速解决方案。在开始和结束之间提取小块,用 yaml 库解析,然后在一行中打印每个对象列表
  • 您也可以使用文本编辑器或 sed 或 python 使用正则表达式来处理它

标签: python python-3.x text copy-paste


【解决方案1】:

用冒号分割行,然后以不同的顺序合并它们。 我添加了一些标志来实现与您的文件中完全相同的标点符号, 然而对于中等大小的数据,我通常使用迭代几个正则表达式或字符串替换

with open('C:\\Users\\Excel\\Desktop\\test_in.txt') as infile, 
    file_start = True
    line = line.strip()
    next(infile)
    next(infile)
    next(infile)
    for line in infile:
        if line.strip() == "Start":
            if file_start:
                file_start = False # write nothing first time
            else:
               outfile.write('\n')
            line_start = True  # starting new line in the output file
        elif not line.strip() == "End":
            if not line_start:  
                outfile.write(", ")

            linestart = False

            line = line.strip(" -")
            s = line.split(": ")
            outfile.write(": ".join(s[::-1]))

【讨论】:

  • 当我运行你的代码时,我得到了这个错误:NameError: name 'line_start' is not defined。我做了一些改变;我无法让这个工作。不过,我认为它非常接近!!!
  • 等等,现在错误消失了。但是,我在第一个“开始”之前收到了文本。我只想要“开始”和“结束”之间的东西,包括“开始”和“结束”锚点。看起来其他一切都很好!谢谢!!
  • 删除前三行。看来您还需要 END 和 START 之间的文本,基本上您只需在新文件中用换行符替换它们
  • 是的,是的,是的。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 2021-12-21
  • 2015-03-31
  • 2019-08-28
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
相关资源
最近更新 更多