gpt4 book ai didi

python - 如何解析括号和缺失值之间有逗号的 CSV

转载 作者:太空宇宙 更新时间:2023-11-03 15:10:04 25 4
gpt4 key购买 nike

我尝试使用 pyparsing 来解析 CSV:

  • 括号(或方括号等)之间的逗号: "a(1,2),b"应返回列表 ["a(1,2)","b"]<
  • 缺失值:“a,b,,c,”应返回列表 ['a','b','','c','']

我找到了一个解决方案,但它看起来“脏”。主要是,Optional 仅包含一种可能的原子。我认为可选应该独立于原子。也就是说,我觉得它应该放在其他地方,例如在 delimitedList 可选参数中,但在我的反复试验中,这是唯一有效且有意义的地方。它可以是任何可能的原子,所以我选择了第一个。

另外,我不完全理解 originalTextFor 正在做什么,但如果我删除它,它就会停止工作。

工作示例:

import pyparsing as pp

# Function that parses a line of columns separated by commas and returns a list of the columns
def fromLineToRow(line):
sqbrackets_col = pp.Word(pp.printables, excludeChars="[],") | pp.nestedExpr(opener="[",closer="]") # matches "a[1,2]"
parens_col = pp.Word(pp.printables, excludeChars="(),") | pp.nestedExpr(opener="(",closer=")") # matches "a(1,2)"
# In the following line:
# * The "^" means "choose the longest option"
# * The "pp.Optional" can be in any of the expressions separated by "^". I put it only on the first. It's used for when there are missing values
atomic = pp.originalTextFor(pp.Optional(pp.OneOrMore(parens_col))) ^ pp.originalTextFor(pp.OneOrMore(sqbrackets_col))

grammar = pp.delimitedList(atomic)

row = grammar.parseString(line).asList()
return row

file_str = \
"""YEAR,a(2,3),b[3,4]
1960,2.8,3
1961,4,
1962,,1
1963,1.27,3"""

for line in file_str.splitlines():
row = fromLineToRow(line)
print(row)

打印:

['YEAR', 'a(2,3)', 'b[3,4]']
['1960', '2.8', '3']
['1961', '4', '']
['1962', '', '1']
['1963', '1.27', '3']

这是正确的方法吗?是否有一种“更干净”的方法来使用第一个原子内的 Optional

最佳答案

由内而外地工作,我明白了:

# chars not in ()'s or []'s - also disallow ','
non_grouped = pp.Word(pp.printables, excludeChars="[](),")

# grouped expressions in ()'s or []'s
grouped = pp.nestedExpr(opener="[",closer="]") | pp.nestedExpr(opener="(",closer=")")

# use OneOrMore to allow non_grouped and grouped together
atomic = pp.originalTextFor(pp.OneOrMore(non_grouped | grouped))
# or based on your examples, you *could* tighten this up to:
# atomic = pp.originalTextFor(non_grouped + pp.Optional(grouped))

originalTextFor 在匹配表达式的前导和尾随边界内重新组合原始输入文本,并返回单个字符串。如果省略此选项,那么您将获得嵌套字符串列表中的所有子表达式,例如 ['a',['2,3']]。您可以通过重复调用 ''.join 重新加入它们,但这会折叠空白(或使用 ' '.join,但是这样存在可能引入空格的相反问题)。

要选择列表的元素,只需在分隔列表的定义中这样说即可:

grammar = pp.delimitedList(pp.Optional(atomic, default=''))

请务必添加默认值,否则空槽将被丢弃。

通过这些更改,我得到:

['YEAR', 'a(2,3)', 'b[3,4]']
['1960', '2.8', '3']
['1961', '4', '']
['1962', '', '1']
['1963', '1.27', '3']

关于python - 如何解析括号和缺失值之间有逗号的 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44289614/

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