如何在Python中拆分记录?

2024-04-27 02:52:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python中的split函数分割记录,但无法达到实际效果。你知道吗

下面是我的.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

任何帮助都将不胜感激,谢谢。你知道吗


Tags: 文件函数txt内容记录split试图用实际效果
1条回答
网友
1楼 · 发布于 2024-04-27 02:52:40

这里是获得所需结果的最简单方法,它只需要来自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)}
"""))

祝你好运。你知道吗

相关问题 更多 >