计算字符串中特定单词的出现数量
我有一个字符串,我正在尝试计算重复其某些部分的次数(名称)。我认为将字符串变成列表是个好主意,因此我可以按索引
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
I have a string and I'm trying to count the number of times certain parts of it are repeated (the names). I thought it would be a good idea to turn the string into a list so I can count the names by index
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))
Output:
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})
Good output:
andy: 2
emma: 2
david: 2
nigel: 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将使用
ast.literal_eval
>在字符串上进行了一些更改,将其加载为列表(关闭括号后添加逗号),然后使用collections.counter
:其他,不太强大的,使用正则是想法。查找在(第二个)之前和之后具有逗号的项目,并进送到
collections.counter
:输出:输出:
I would use
ast.literal_eval
with a bit of change on the string to load it as list (adding a comma after closing brackets), then usecollections.Counter
:Other, less robust, idea using a regex. Find the item that has both a comma before and after (second one) and feed to
collections.Counter
:output: