[英]Python parsing CSV string with possible sets
我有一個 CSV 字符串,其中一些項目可能用{}
括起來,里面有逗號。 我想收集列表中的字符串值。
在列表中收集值的最pythonic 方法是什么?
示例 1: 'a,b,c'
,預期輸出['a', 'b', 'c']
示例 2: '{aa,ab}, b, c'
,預期輸出['{aa,ab}','b','c']
示例 3: '{aa,ab}, {bb,b}, c'
,預期輸出['{aa,ab}', '{bb,b}', 'c']
我曾嘗試使用s.split(',')
,它適用於示例 1,但會在案例 2 和 3 中搞砸。
我相信這個問題( 在 python 中如何拆分但忽略帶引號的字符串中的分隔符? )與我的問題非常相似。 但我無法弄清楚要使用的正確正則表達式語法。
解決方案實際上非常相似:
import re
PATTERN = re.compile(r'''\s*((?:[^,{]|\{[^{]*\})+)\s*''')
data = '{aa,ab}, {bb,b}, c'
print(PATTERN.split(data)[1::2])
會給:
['{aa,ab}', '{bb,b}', 'c']
一種更易讀的方式(至少對我而言)是解釋您要查找的內容:括號 { } 之間的內容或僅包含字母數字字符的內容:
import re
examples = [
'a,b,c',
'{aa,ab}, b, c',
'{aa,ab}, {bb,b}, c'
]
for example in examples:
print(re.findall(r'(\{.+?\}|\w+)', example))
它打印
['a', 'b', 'c']
['{aa,ab}', 'b', 'c']
['{aa,ab}', '{bb,b}', 'c']
請注意,沒有必要使用正則表達式,您可以使用純 Python:
s = '{aa,ab}, {bb,b}, c'
commas = [i for i, c in enumerate(s) if c == ',' and \
s[:i].count('{') == s[:i].count('}')]
[s[2:b] for a, b in zip([-2] + commas, commas + [None])]
#['{aa,ab}', '{bb,b}', 'c']
一種更簡單的純 python 方法用 "" 替換 {}:
def parseCSV(string):
results = []
current = ''
quoted = False
quoting = False
for i in range(0, len(string)):
currentletter = string[i]
if currentletter == '"':
if quoted == True:
if quoting == True:
current = current + currentletter
quoting = False
else:
quoting = True
else:
quoted = True
quoting = False
else:
shouldCheck = False
if quoted == True:
if quoting == True:
quoted = False
quoting = False
shouldCheck = True
else:
current = current + currentletter
else:
shouldCheck = True
if shouldCheck == True:
if currentletter == ',':
results.append(current)
current = ''
else:
current = current + currentletter
results.append(current)
return results
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.