我有一些代码可以将大文件复制/粘贴到我需要的解析文件中。这是一个工作脚本。
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)
现在,我试图弄清楚如何转置每个测试 block ,并多次交换相邻数据点。也许这需要一个 dta 框架,我不太确定。
这是之前的图片。
这是一个后像。
这是我的示例文本。
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 的了解还不够,无法确定这是否是正确的方法。感谢您抽出时间。
最佳答案
用冒号分割行,然后以不同的顺序合并它们。 我添加了一些标志来实现与您的文件中完全相同的标点符号, 但对于中等大小的数据,我通常使用多个正则表达式或字符串替换进行迭代
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]))
关于python - 尝试在开始点和结束点之间复制/粘贴文本、转置和交换数据点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52911702/