gpt4 book ai didi

python - 如何在 Python 中拆分记录?

转载 作者:太空宇宙 更新时间:2023-11-04 02:01:46 24 4
gpt4 key购买 nike

我正在尝试使用 split 函数在 python 中拆分记录,但无法实现实际结果。

下面是我的 .txt 文件的内容:

10000  {(10000,200,300,A),(10000,200,300,B)},{(10000,200,300,C),(10000,200,300,D)}
10001 {(10001,200,300,E),(10001,200,300,F)},{(10001,200,300,G),(10001,200,300,H)}

这是期望的输出:

10000  10000,200,300,A
10000 10000,200,300,B
10000 10000,200,300,C
10000 10000,200,300,D
10001 10001,200,300,E
10001 10001,200,300,F
10001 10001,200,300,G
10001 10001,200,300,H

如有任何帮助,我们将不胜感激。

最佳答案

这是获得所需结果的最简单方法,它只需要 re 包中的 subfindall 方法即可工作。

from re import sub, findall

string = """
10000 {(10000,200,300,A),(10000,200,300,B)},{(10000,200,300,C),(10000,200,300,D)}
10001 {(10001,200,300,E),(10001,200,300,F)},{(10001,200,300,G),(10001,200,300,H)}
"""

# our results go here
results = []

# loop through each line in the string
for line in string.split("\n"):
# get rid of leading and trailing whitespace
line = line.strip()
# ignore empty lines
if len(line) > 0:
# get the line's id
id = line.split("{")[0].strip()
# get all values wrapped in parenthesis
for match in findall("(\(.*?\))", string):
# add the string to the results list
results.append("{} {}".format(id, sub(r"\{|\}", "", match)))

# display the results
print(results)

下面是函数形式的相同代码:

from re import sub, findall

def get_records(string):
# our results go here
results = []
# loop through each line in the string
for line in string.split("\n"):
# get rid of leading and trailing whitespace
line = line.strip()
# ignore empty lines
if len(line) > 0:
# get the line's id
id = line.split("{")[0].strip()
# get all values wrapped in parenthesis
for match in findall("(\(.*?\))", string):
# add the string to the results list
results.append("{} {}".format(id, sub(r"\{|\}", "", match)))
# return the results list
return results

然后您将像这样使用该函数:

# print the results
print(get_records("""
10000 {(10000,200,300,A),(10000,200,300,B)},{(10000,200,300,C),(10000,200,300,D)}
10001 {(10001,200,300,E),(10001,200,300,F)},{(10001,200,300,G),(10001,200,300,H)}
"""))

祝你好运。

关于python - 如何在 Python 中拆分记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55546053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com