我有一個字串,我正在嘗試計算其中某些部分重復的次數(名稱)。我認為將字串轉換為串列是個好主意,這樣我就可以按索引計算名稱
from collections import Counter
string = "['673', 'andy', '05/05/16']['986', 'emma', '16/01/18']['147', 'david', '05/04/16']['996', 'nigel', '26/04/17']['209', 'emma', '04/03/17']['619', 'david', '18/07/18']['768', 'andy', '18/11/15']"
string_list = list(string)
print(Counter(string_list))
輸出:
Counter({"'": 42, '1': 15, ',': 14, ' ': 14, '/': 14, '0': 10, '6': 9, '[': 7, ']': 7, '7': 6, 'a': 6, 'd': 6, '8': 6, '9': 5, '5': 4, 'm': 4, '4': 4, 'n': 3, 'e': 3, 'i': 3, '3': 2, 'y': 2, 'v': 2, '2': 2, 'g': 1, 'l': 1})
良好的輸出:
andy: 2
emma: 2
david: 2
nigel: 1
uj5u.com熱心網友回復:
我會ast.literal_eval在字串上進行一些更改以將其加載為串列(在右括號后添加逗號),然后使用collections.Counter:
from ast import literal_eval
from collections import Counter
out = Counter(x[1] for x in literal_eval(string.replace(']', '],')))
使用正則運算式的其他不太健壯的想法。找到前后都有逗號的專案(第二個)并提供給collections.Counter:
import re
from collections import Counter
out = Counter(m.group(1) for m in re.finditer(r", '([^'] )',", string))
輸出:
Counter({'andy': 2, 'emma': 2, 'david': 2, 'nigel': 1})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/492560.html
標籤:Python python-3.x 细绳 柜台
上一篇:NodeJscsv-parseawait在on('data')
下一篇:提取俄羅斯護照號碼的正則運算式
