【问题标题】:How do I split records in Python?如何在 Python 中拆分记录?
【发布时间】:2019-04-06 04:58:14
【问题描述】:

我正在尝试使用 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

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 听起来你需要先解析你的文本文件
  • 是否要将输出存储在文本文件中?
  • 我想把它存储在excel文件中
  • 到目前为止你尝试了什么?

标签: python python-3.x split


【解决方案1】:

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

祝你好运。

【讨论】:

  • @BeekashMohanty 非常欢迎您,如果答案有效,请不要忘记使用向下箭头下方的绿色勾号将其标记为已接受。
  • 你可以用if line:代替if len(line) > 0:
  • @RoadRunner 不只是检查线路是否存在/“真实性”
  • @LogicalBranch 是的。如果一行不为空 -> true,否则 -> false。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-19
  • 1970-01-01
  • 1970-01-01
  • 2012-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多