计算字符串中特定单词的出现数量

发布于 2025-02-08 16:37:22 字数 716 浏览 1 评论 0原文

我有一个字符串,我正在尝试计算重复其某些部分的次数(名称)。我认为将字符串变成列表是个好主意,因此我可以按索引

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱的故事 2025-02-15 16:37:22

我将使用 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})

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 use collections.Counter:

from ast import literal_eval
from collections import Counter

out = Counter(x[1] for x in literal_eval(string.replace(']', '],')))

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:

import re
from collections import Counter

out = Counter(m.group(1) for m in re.finditer(r", '([^']+)',", string))

output:

Counter({'andy': 2, 'emma': 2, 'david': 2, 'nigel': 1})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文