我正在分析從收據中獲得的銷售資料。所有購買的物品都在一列中作為一個字串,如下所示:
'1 x Sandwich, "2 x Coffee, with cream", 1 x Apple pie'
我希望將所有物品分開來計算購買的物品數量。簡單的string.split(',')不行,因為某些專案的名稱中也有逗號。幸運的是,這些名稱是用雙引號封裝的,而“普通”名稱則不是。
如何替換雙引號內的逗號而不是逗號分隔專案?
例如,如果名稱中的這些逗號變為冒號,則可以使用 決議字串string.split()。所以所需的輸出將是這樣的:
'1 x Sandwich, "2 x Coffee: with cream", 1 x Apple pie'
可能還有其他解決方案,但這個問題讓我開始考慮替換非常具體的字符。
uj5u.com熱心網友回復:
text = '1 x Sandwich, "2 x Coffee, with cream", 1 x Apple pie'
def comma_changer(text):
text = list(text)
quote_counter = 0
for i,char in enumerate(text):
if char == '"':
quote_counter =1
elif char == ",":
if quote_counter%2 == 1:
text[i] = ":"
return("".join(text))
comma_changer(text) #'1 x Sandwich, "2 x Coffee: with cream", 1 x Apple pie'
uj5u.com熱心網友回復:
您需要嘗試告訴它用特定字符分隔它。在這種情況下,請嘗試 string.split('"')
uj5u.com熱心網友回復:
您的輸入無效,因為缺少一個 close"和一個缺少 opening "。
"1 x Sandwich, "2 x Coffee, with cream", 1 x Apple pie"
^ ^
我在csv這里使用 Pythons 模塊。該選項非常重要,skipinitialspace因為后面有空白字符(空格),,這在 CSV 檔案中是不常見的。
#!/usr/bin/env python3
import io
import csv
your_invalid_input = '"1 x Sandwich, "2 x Coffee, with cream", 1 x Apple pie"'
valid_input = '"1 x Sandwich", "2 x Coffee, with cream", "1 x Apple pie"'
# this simulates a file object
raw_data = io.StringIO(valid_input)
csv_reader = csv.reader(raw_data,
delimiter=',',
skipinitialspace=True)
for line in csv_reader:
print(line)
輸出是
['1 x Sandwich', '2 x Coffee, with cream', '1 x Apple pie']
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473926.html
上一篇:如何調節中弦
