pandas 在python中逐列转换输入代码

zf2sa74q  于 2023-09-29  发布在  Python
关注(0)|答案(2)|浏览(111)

我有一个输入文件的格式看起来像下面,(input.txt)
假设此格式为随机十六进制数据,如下所示:

  1. 20 3h 4f 57 56 37
  2. 4a 2d 33 45 10 2a
  3. 23 47 4c

我想把这个文件转换成另一种格式如下:(output.txt)

  1. hform_param00 = 20
  2. hform_param01 = 3h
  3. hform_param02 = 4f
  4. .
  5. .
  6. hform_param05 = 37
  7. hform_param06 = 4a
  8. .
  9. .
  10. hform_param12 = 23
  11. hform_param13 = 47
  12. hform_param14 = 4c

我该怎么办?我已经考虑过pandas框架,但是输入的整体结构与我预期的完全不同。
任何解决方案或提示将非常感谢!

pnwntuvh

pnwntuvh1#

首先阅读txt文件,将任何新行(\n)替换为空格。然后对任何空格使用字符串拆分方法将字符串转换为值列表。

  1. f = open("input.txt", "r")
  2. input_txt = f.read()
  3. input_txt = input_txt.replace('\n', ' ').split(' ')

如果你想把它存储在一个输出文本文件中,你可以遍历每个列表条目。在output.txt文件的新行中写入每个条目及其关联索引

  1. f = open("output.txt", "w")
  2. for idx, val in enumerate(input_txt):
  3. f.write(f"hform_param{str(idx).zfill(2)} = {val}\n")
  4. f.close()

输出量:

zpqajqem

zpqajqem2#

下面是另一个使用 * with * 语句的示例...

  1. string = ""
  2. index = 0
  3. with open("input.txt", "r") as f:
  4. for line in f:
  5. clean = line.replace('\n', '')
  6. field = clean.split(" ")
  7. for item in field:
  8. if index < 10:
  9. string += "hform_param0" + str(index) + " = " + item + "\n"
  10. index += 1
  11. continue
  12. string += "hform_param" + str(index) + " = " + item + "\n"
  13. index += 1
  14. with open("output.txt", "w") as f:
  15. f.write(string)

展开查看全部

相关问题