我有一个文本文件,其中包含任意(非 Python)四行 block 列表,如下所示:
WHAT
EVER
0.00000904
17577
FOO
BAR
7.00000031
426
该文件包含数千个这样的 block 。如何将文件中的数据转换为列表字典,其中键是每个 block 的前两行,连接起来,接下来的两行是列表值?例如:
{'WHATEVER': [0.00000904, 17577], 'FOOBAR': [7.00000031, 426]}
最佳答案
尝试以下操作:
import re
# Open the file
data = open('odd_lines.txt').read()
# Split on the double newline characters
data = data.split("\n\n")
# Split each element of the data list on the newline characters followed by a float
data = [re.split("\n(\d+\.\d+)", x) for x in data]
# Put the data in a dictionary with the key being the first element of each element of the data list.
# Make sure to replace the newline character with an empty space
output = {x[0].replace("\n",""):[float(y) for y in x[1:]] for x in data}
print(output)
这应该产生:
#{'FOOBAR': [7.00000031, 426], 'WHATEVER': [0.00000904, 17577]}
以下是起始文件 (odd_lines.txt
):
WHAT
EVER
0.00000904
17577
FOO
BAR
7.00000031
426
我希望这会有所帮助。
关于Python:将文本文件的行转换并连接到具有列表值的字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41081425/